【发布时间】:2016-12-12 02:24:38
【问题描述】:
我从如下所示的 API 获取 JSON:
{
"Items": {
"Item322A": [{
"prop1": "string",
"prop2": "string",
"prop3": 1,
"prop4": false
},{
"prop1": "string",
"prop2": "string",
"prop3": 0,
"prop4": false
}],
"Item2B": [{
"prop1": "string",
"prop2": "string",
"prop3": 14,
"prop4": true
}]
},
"Errors": ["String"]
}
我已经尝试了几种方法来在 c# 对象中表示这个 JSON(这里列出的太多了)。我尝试过使用列表和字典,这是我最近尝试表示的示例:
private class Response
{
public Item Items { get; set; }
public string[] Errors { get; set; }
}
private class Item
{
public List<SubItem> SubItems { get; set; }
}
private class SubItem
{
public List<Info> Infos { get; set; }
}
private class Info
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public int Prop3 { get; set; }
public bool Prop4 { get; set; }
}
这是我用来反序列化 JSON 的方法:
using (var sr = new StringReader(responseJSON))
using (var jr = new JsonTextReader(sr))
{
var serial = new JsonSerializer();
serial.Formatting = Formatting.Indented;
var obj = serial.Deserialize<Response>(jr);
}
obj 包含 Items 和 Errors。而Items 包含SubItems,但SubItems 是null。因此,除了Errors 之外,实际上没有任何东西被反序列化。
应该很简单,但由于某种原因我无法找出正确的对象表示
【问题讨论】:
标签: c# json json.net deserialization json-deserialization