我们正在调用一个返回 JSON 数据的 API,其结构如下:
[
{
"firstName": "Bill",
"lastName": "Gates",
"email": "[email protected]"
},
{
"firstName": "Steve",
"lastName": "Balmer",
"email": "[email protected]"
}
]
复制此数据并使用 Visual Studio 2022 中的“将 JSON 粘贴为类”选项后,我们得到以下类:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
}
如果我们运行以下测试,我们的员工对象包含 2 个元素,但每个元素的值为 NULL。
string sJSON = @"[{""firstName"":""Bill"",""lastName"":""Gates"",""email"":""[email protected]""},{""firstName"":""Steve"",""lastName"":""Balmer"",""email"":""[email protected]""}]";
Rootobject[] employees = JsonSerializer.Deserialize<Rootobject[]>(sJSON);
知道这里出了什么问题吗?
首先,你的班级应该有不同的结构:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
然后反序列化使用:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var employees = System.Text.Json.JsonSerializer.Deserialize<Employee[]>(json, options);
你也可以在这里看看JsonPropertyAttribute
基于您的 Json Rootobject 应该是一个数组。 您可以使用 Convert Json to C# Classes Online 为您的 Json 生成模型。