【发布时间】:2021-09-06 04:17:05
【问题描述】:
如何将 Json 反序列化为具有节点键 ID 的 C# 对象?例如:
{
"people" : {
"1": {
"firstname": "jim",
"lastname": "brown"
},
"2": {
"firstname": "kathy",
"lastname": "jones"
}
}
}
将序列化到这个 C# 类中
public class JsonRoot {
public List<Person> People { get; set; }
}
public class Person {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
是否可以使用自定义通用转换器或 json 属性来做到这一点?
【问题讨论】:
-
将
List<Person>替换为Dictionary<string, Person>。 -
见:Query or deserialize json with dynamic keys using System.Text.Json,看起来是重复的,同意吗?还是您需要将 JSON 对象反序列化为列表?
-
您也许可以在 .NET 5 中使用
Dictionary<int, Person>,请参阅 devblogs.microsoft.com/dotnet/whats-next-for-system-text-json/…: Support non-string dictionary keys。 -
您的 Json 字符串和类不匹配。
people是一个对象/字典,其键是数字,其值没有Id属性。您必须使用 matching 类对其进行反序列化,然后将它们映射到您想要的类 -
Dictionary
可以满足我的需要,谢谢!
标签: asp.net json asp.net-core json.net system.text.json