【发布时间】:2026-01-25 00:50:01
【问题描述】:
我正在尝试将 Json 反序列化为 Student 的 List 对象,该对象由 studentName 和 studentId 组成。我确实得到了大约 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; }
}
【问题讨论】:
-
请添加minimal reproducible example 并用您使用的语言标记它。
标签: c# json microsoft-graph-api