Search code examples
jsonxamarinrefit

Xamarin Refit - Newtonsoft.Json.JsonSerializationException


I have some problems with JSON Serialization. When I try to deserialize my JSON Object, it returns me this error :

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Project.Models.BookModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

My problem here is that I have to deserialize my object in two different ways : In a JSON array(e.g.[1,2,3]) to extract "_id", "user" and "name", and then in a JSON array(e.g.["name":"value"]) to extract "books". And I don't know how to do it. Or more precisely, I don't know if it's posible with Refit.

Here is my JSON :

[
{
    "_id": "5c014a1e43b6804ed7b642b2",
    "__v": 0,
    "user": "5c014a1d43b6804ed7b642b1",
    "name": "Favoris",
    "books": [
        {
            "_id": "5a8f12e16a16fa06d1f5b0cb",
            "title": "Harry Potter et la Chambre des Secrets",
            "author": {
                "_id": "5a8f12e16a16fa06d1f5b0bd",
                "name": "J K Rowling",
                "__v": 0
            },
            "literaryGenre": "Juvenile Fiction",
            "isbn": 9781781101049,
            "externalImage": "...",
            "__v": 0,
            "content": {
                "brief": "test1"
            }
        },
        {
            "_id": "5a8f12e16a16fa06d1f5b0d0",
            "title": "Harry Potter et la Coupe de Feu",
            "author": {
                "_id": "5a8f12e16a16fa06d1f5b0bd",
                "name": "J K Rowling",
                "__v": 0
            },
            "literaryGenre": "Juvenile Fiction",
            "isbn": 9781781101063,
            "externalImage": "...",
            "__v": 0,
            "content": {
                "brief": "test2"
            }
        }
    ]
}
]

Here is my code :

public async void ViewLibrary()
    {
        IProjectApi response = ProjectRepository.Instance.ProjectApi;
        List<LibraryModel> library = await response.GetLibrary("5c014a1d43b6804ed7b642b1");

        this.LibraryItems = library;
    }

And my object LibraryModel :

public class LibraryModel
{
    public string _id { get; set; }

    public string user { get; set; }

    public string name { get; set; }

    public BookModel books { get; set; }
}

And my method GetLibrary :

    [Get("/api/library/user/{UserId}")]
Task<List<LibraryModel>> GetLibrary(string UserId);

Solution

  • Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Project.Models.BookModel' because the type requires a JSON object (e.g. {"name":"value"})

    In json result your BookModel returning multiple records, so it should be defined as List<BookModel>.

    In LibraryModel try using public List<BookModel> books { get; set; }.