Home > other >  Cannot deserialize the current JSON - DeserializeObject - Bad model
Cannot deserialize the current JSON - DeserializeObject - Bad model

Time:07-12

I try downloading data from API, but I get an error when DeserializeObject

I suppose I have a badly built model: ObjectResponse

but I can't think of how else to build it

I use Newtonsoft.Json

Controller

private async Task<Response<IEnumerable<ObjectResponse>>> GetItemsAsync(string uri)
{
    var result = await _client.GetStringAsync(uri);

    return JsonConvert.DeserializeObject<Response<IEnumerable<ObjectResponse>>>(result);
}

in result I have:

"{"success":true,"data":{"leasingItems":[],"suspectedItems":[]}}"

Models

public class Response<T>
{
    public bool Success { get; set; }
    public T Data { get; set; }
    public IEnumerable<Error> Errors { get; set; }
}

public class ObjectResponse
{
    public string[]? leasingItems { get; set; }
    public string[]? suspectedItems { get; set; }
}

Error:

One or more errors occurred. (Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[Swip.Core.DTO.SwipSearchSuspect]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'data.leasingItems', line 1, position 39.)

Inner Exception 1: JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[Swip.Core.DTO.SwipSearchSuspect]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'data.leasingItems', line 1, position 39.

CodePudding user response:

The data property in the JSON was an ObjectResponse object, but not an ObjectResponse array.

Remove the IEnumerable<>.

return JsonConvert.DeserializeObject<Response<ObjectResponse>>(result);

And apply the JsonProperty attribute.

public class Response<T>
{
  [JsonProperty("success")]
  public bool Success { get; set; }
  [JsonProperty("data")]
  public T Data { get; set; }
  public IEnumerable<Error> Errors { get; set; }
}
  • Related