Home > Back-end >  How to fix error: JsonSerializationException: Cannot deserialize the current JSON object
How to fix error: JsonSerializationException: Cannot deserialize the current JSON object

Time:01-14

This is what the body looks like:

{
  "_total": 3,
  "users": [
    {
      "username": "person1",
      "points": 3
    },
    {
      "username": "person2",
      "points": 2
    },
    {
      "username": "person3",
      "points": 1
    }
  ]
}

The code:

public class UserData
{
 public string username { get; set; }
 public int points { get; set; }
}
using (var response = await client.SendAsync(request))
 {
  response.EnsureSuccessStatusCode();
  var body = await response.Content.ReadAsStringAsync();

  var data = JsonConvert.DeserializeObject<List<UserData>>(body); 
  foreach (UserData userdata in data) 
  {
   Debug.Log(userdata.username   ": "   userdata.points);
  }
 }

The Error:

JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[UserData]' 
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.

CodePudding user response:

The class does not match the JSON structure, hence you are getting JsonSerializationException Exception.
Your model should look something like that:

public class RootClass
{
    public int _total { get; set; }
    public List<User> users { get; set; }
}

public class User
{
    public string username { get; set; }
    public int points { get; set; }
}

Than you can do this:

using (var response = await client.SendAsync(request))
 {
  response.EnsureSuccessStatusCode();
  var body = await response.Content.ReadAsStringAsync();

  var data = JsonConvert.DeserializeObject<RootClass>(body); 
  foreach (User userdata in data.users) 
  {
   Debug.Log(userdata.username   ": "   userdata.points);
  }
 }

CodePudding user response:

you can parse a json string at first and after this to deserialize it to a list of UserData

var data = JObject.Parse(body)["users"].ToObject<List<UserData>>(); 
  • Related