反序列化后获取null值



我试图从Web API获取JSON数据,然后在MVC应用程序中以表格形式显示。但是在使用反序列化后接收到null值。

JSON文件:

[{
"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 ;
}

我试图获取响应中的值(res(,但从OStudents获取null

更新

基于最新的JSON响应,它是一个Root数组。

您需要将JSON反序列化为List<Root>,然后从数组中提取第一个Root对象。然后从Root对象中提取Students列表。

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

完成代码:

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;
}

您也可以使用JArray作为:

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>>();
}

相关内容

  • 没有找到相关文章

最新更新