【问题标题】:Deserilizing the json to list of an object throwing error. Cannot deserialize the current JSON object (e.g. {"name":"value"})将 json 反序列化为对象抛出错误的列表。无法反序列化当前 JSON 对象(例如 {"name":"value"})
【发布时间】: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; }
}

【问题讨论】:

标签: c# json microsoft-graph-api


【解决方案1】:

JSON 响应包含一个 value: 属性,该属性包含学生作为数组数据。因此,您需要创建一个具有List&lt;Student&gt; 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

【讨论】:

  • Peter 感谢您的帮助,它确实解决了我的问题。我确实尝试了您提到的一些方法,但从未想过我必须将 List 属性名称更改为 StudentListHolder 类中的值
最近更新 更多