我正在嘗試將 Json 反序列化為由 studentName 和 studentId 組成的 Student 的 List 物件。我確實收到了大約 200 名學生的 jsonResponse,但是當我開始反序列化時,出現以下錯誤。我對此錯誤進行了研究,該問題的修復與我擁有的代碼類似,因此我不確定是什么問題。
無法將當前 JSON 物件(例如 {"name":"value"})反序列化為型別“System.Collections.Generic.List`1[MyApp.Models.Student]”,因為該型別需要一個 JSON 陣列(例如 [1, 2,3]) 以正確反序列化。
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;
}
以下是來自 Microsoft Graph Api 的 JSON 回應
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(studentName,studentId)",
"value": [
{"studentName":"Radha,NoMore","studentId":"420"},
{"studentName":"Victoria, TooMuch","studentId":"302"}
]
}
C#學生類:
public class Student
{
public string studentName { get; set; }
public string studentId { get; set; }
}
uj5u.com熱心網友回復:
JSON 回應包含一個value:屬性,該屬性包含作為陣列資料的學生。因此,您需要創建一個具有List<Student> value屬性的附加類,反序列化為該類,然后您可以使用該value屬性中的學生串列,如下所示:
var listHolder = JsonConvert.DeserializeObject<StudentListHolder>(jsonResponse);
var list = listHolder.value;
foreach (var student in list)
{
Console.WriteLine(student.studentId " -> " student.studentName);
}
這是額外的類:
public class StudentListHolder // pick any name that makes sense to you
{
public List<Student> value { get; set; }
}
作業演示(.NET Fiddle):https : //dotnetfiddle.net/Lit6Er
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389627.html
