Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix error: JsonSerializationException: Cannot deserialize the current JSON object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
  }
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading