0

I need the usernames and their points from the response.

This is what the body looks like:

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

My Code:

List<string> data;
using (var response = await client.SendAsync(request))
 {
  response.EnsureSuccessStatusCode();
  var body = await response.Content.ReadAsStringAsync();

  data = JsonConvert.DeserializeObject<List<string>>(body); 
  foreach (var i in data) {
   Debug.Log(i);
  }
}

I would like to save the body to the List data and get the usernames and their points from there.

Elefank
  • 41
  • 4

1 Answers1

0

You can create a custom class to hold the data from the JSON response, like so:

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

Then, you can change your deserialization code to use this class instead of a List of strings:

List<UserData> data;
using (var response = await client.SendAsync(request))
{
    response.EnsureSuccessStatusCode();
    var body = await response.Content.ReadAsStringAsync();

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

This should allow you to access the username and points from the JSON response using the "data" variable.

  • I got this error message: 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. – Elefank Jan 13 '23 at 18:16