簡體   English   中英

將 json 反序列化以列出 object 拋出錯誤。 無法反序列化當前的 JSON object (eg {"name":"value"})

[英]Deserilizing the json to list of an object throwing error. Cannot deserialize the current JSON object (e.g. {"name":"value"})

我正在嘗試反序列化 Json 以列出 StudentName 和 studentId 的 object。 我確實得到了大約 200 名學生的 jsonResponse,但是當我開始反序列化時,我得到了以下錯誤。 我對此錯誤進行了研究,該問題的修復與我擁有的代碼相似,因此我不確定出了什么問題。

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.Models.Student]' because the type requires a JSON array (eg [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# 學生 Class:

public class Student
{
    public string studentName { get; set; } 
    public string studentId { get; set; }
}

JSON 響應包含一個value:屬性,該屬性包含學生作為數組數據。 因此,您需要額外創建一個具有List<Student> value屬性的 class,反序列化為該 class,然后您可以使用value屬性中的學生列表,如下所示:

var listHolder = JsonConvert.DeserializeObject<StudentListHolder>(jsonResponse);
var list = listHolder.value;
foreach (var student in list)
{
    Console.WriteLine(student.studentId + " -> " + student.studentName);
}

這是額外的 class:

public class StudentListHolder // pick any name that makes sense to you
{
    public List<Student> value { get; set; }
}

工作演示(.NET Fiddle): https://dotnetfiddle.net/Lit6Er

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM