Getting null value after deserialization

Viewed 93

I'm trying to get JSON data from Web API and then show it in tabular form in the MVC application. But receiving null values after using deserialization.

JSON file :

[{
  "Students": [
    {
      "id": 1,
      "name": "Ravi",
      "department": "IT"
    },

    {
      "id": 2,
      "name": "Raj",
      "department": "hr"
    },
    {
      "id": 3,
      "name": "avi",
      "department": "it"
    },
    {
      "id": 4,
      "name": "rome",
      "department": "HR"
    }
  ]
}]
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
} 
   

[HttpGet]
public async Task<List<Student>> GetAllStudents()
{
            
    /// Ostudent = new Student()
    using (var httpclient  = new HttpClient())
    {
        using (var response = await httpclient.GetAsync("https://localhost:7232/api/Student"))
        {
            string res = await response.Content.ReadAsStringAsync()
                OStudents = JsonConvert.DeserializeObject<List<Student>>(res);
        }
    }
    return OStudents ;
}

I'm trying to get value in response (res) but getting null from OStudents.

1 Answers

Updated

Based on the latest JSON response, it is an array of Root.

You need to deserialize the JSON as the List<Root> and then extract the first Root object from the array. Then extract the Students list from the Root object.

public class Root
{
    public List<Student> Students { get; set; }
}
List<Root> roots = JsonConvert.DeserializeObject<List<Root>>(res);
List<Student> OStudents = roots[0].Students;

Completed code:

public async Task<List<Student>> GetAllStudents()
{
            
    List<Student> OStudents = new List<Student>();
    using (var httpclient  = new HttpClient())
    {
        using (var response = await httpclient.GetAsync("https://localhost:7232/api/Student"))
        {
            string res = await response.Content.ReadAsStringAsync();
            List<Root> roots = JsonConvert.DeserializeObject<List<Root>>(res);
            OStudents = roots[0].Students;
        }
    }
    return OStudents;
}

You may also work with JArray as:

using Newtonsoft.Json.Linq;

List<Student> OStudents = new List<Student>();
JArray jArray = JArray.Parse(json);
if (jArray.Count > 0)
{
    OStudents = jArray
        .First
        .SelectToken("Students")
        .ToObject<List<Student>>();
}
Related