Home > database >  Deserilizing the json to list of an object throwing error. Cannot deserialize the current JSON objec
Deserilizing the json to list of an object throwing error. Cannot deserialize the current JSON objec

Time:12-22

I am trying to deserialize the Json to List object of Student which conister of studentName and studentId. I do get the jsonResponse with around 200 students but when I get to deserialize I got the below error. I did reserch for this error and the fix for the issue is similar to the code that I have so I am not sure what is wrong.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.Models.Student]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

public static async Task<List<Student>> GetUserInfo()
{
    var token = await AccessToken.GetGraphAccessToken();
    // Construct the query
    HttpClient client = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Globals.MicrosoftGraphUsersApi);
    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

    // Ensure a successful response
    HttpResponseMessage response = await client.SendAsync(request);
    response.EnsureSuccessStatusCode();

    // Populate the data store with the first page of groups
    string jsonResponse = await response.Content.ReadAsStringAsync();
    var students = JsonConvert.DeserializeObject<List<Student>>(jsonResponse);

    return students;   
}

Below is the JSON response from Microsoft Graph Api

{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(studentName,studentId)",
  "value": [
    {"studentName":"Radha,NoMore","studentId":"420"},
    {"studentName":"Victoria, TooMuch","studentId":"302"}
  ]
}

C# student Class:

public class Student
{
    public string studentName { get; set; } 
    public string studentId { get; set; }
}

CodePudding user response:

The JSON response contains a value: property, and that property contains the students as array data. Therefore you'll need to make an additional class that has a List<Student> value property, deserialize to that class, and then you can use the List of Students that is in the value property, as follows:

var listHolder = JsonConvert.DeserializeObject<StudentListHolder>(jsonResponse);
var list = listHolder.value;
foreach (var student in list)
{
    Console.WriteLine(student.studentId   " -> "   student.studentName);
}

This is the additional class:

public class StudentListHolder // pick any name that makes sense to you
{
    public List<Student> value { get; set; }
}

Working demo (.NET Fiddle): https://dotnetfiddle.net/Lit6Er

  • Related