我有一个像这样的JSON类
{
"Items": {
"Item_1A": {
"prop1": "string",
"prop2": "string",
"prop3": 1,
"prop4": [{
"prop_x": 100
},
{
"prop_y": 200
}]
},
"Item2B": {
"prop1": "string",
"prop2": "string",
"prop3": 14,
"prop4": [{
"prop_z": 300
}]
}
}
}
我怎么能把它变成C#类?这是我到目前为止:
public class Info
{
public string prop1 {get;set;}
public string prop2 {get;set;}
public int prop3 {get;set;}
public Dictionary<string, List<int>> prop4 {get;set;}
}
public class Response
{
public Dictionary<string, List<Info>> Item {get;set;}
}
我试图按照这个链接,但没有工作Deserialize nested JSON into C# objects
您的数据模型应如下所示:
public class Info
{
public string prop1 {get;set;}
public string prop2 {get;set;}
public int prop3 {get;set;}
// Modified from
//public Dictionary<string, List<int>> prop4 {get;set}
public List<Dictionary<string, int>> prop4 {get;set;}
}
public class Response
{
// Modified from
//public class Dictionary<string, List<Info>> Item {get;set;}
public Dictionary<string, Info> Items {get;set;}
}
笔记:
Response.Item
应该被命名为Items
。"Items"
是一个具有可变命名的对象值属性的对象:
{
"Items": {
"Item_1A": { },
"Item2B": { }
}
}
这应该被建模为适合非收集类型Dictionary<string, T>
的T
。假设您正在使用json.net,请参阅Serialization Guide: Dictionaries了解详情。如果没有,javascriptserializer表现相似。
您的数据模型public class Dictionary<string, List<Info>> Items
适用于具有可变命名的数组值属性的对象:
{
"Items": {
"Item_1A": [{ },{ }],
"Item2B": [{ }]
}
}
但这不是你拥有的。"prop4"
是一个包含具有可变命名对象值属性的对象的数组,例如:
"prop4": [ // Outer container is an array
{ // Inner container is an object
"prop_x": 100
},
{
"prop_y": 200
}
]
因此,应使用List<T>
等集合作为外部泛型类型:
public List<Dictionary<string, int>> prop4 {get;set;}
见Serialization Guide: IEnumerable, Lists, and Arrays。Dictionary<string, T>
属性。样品工作小提琴here。
这是一个在json之后创建代理类的技巧:
首先,要确保它是有效的JSON,请访问此网站并运行验证器:https://jsonlint.com/
如果没问题,有一些工具可以直接将json和xml转换为c#代理类,如:http://json2csharp.com/:https://xmltocsharp.azurewebsites.net/
现在你去!只需将它们复制到您的模型并开始使用它。
只是对您的模型进行一些小改动。你的prop4
是一个列表或数组。
public class Info
{
public string prop1 {get;set;}
public string prop2 {get;set;}
public int prop3 {get;set;}
public List<Dictionary<string, List<int>>> prop4 {get;set}
}
public class Response
{
public class Dictionary<string, Info> Items {get;set;} // Should be named Items
}
你的prop4
是一个Dictionary<string, List<int>>
,在序列化时看起来像这样(为了简洁,我在发出的JSON中省略了$type
属性):
{
"X": {
"$values": [ 1, 2 ]
},
"Y": {
"$values": [ 3, 4 ]
}
}
你的JSON虽然形成良好,但“形状”错误。它看起来更像是一个包含一个项目字典的数组。
在上面的JSON中,X
和Y
是字典中的键,它是用JSON建模的“常规对象”。 $values
表示每个键的整数列表。