【发布时间】:2017-11-15 21:44:21
【问题描述】:
我在 C# 控制台应用程序中使用一些 JSON,对于一些数据,有一系列选项。示例 JSON:
{
"FIELD_NAME": "Survey",
"VALUE": "",
"FIELD_ID": 1234,
"OPTIONS":[
{ "VALUE": "GENERAL", "DISPLAY_ORDER": 1, "DISPLAY": "GENERAL" },
{ "VALUE": "HPEFS", "DISPLAY_ORDER": 3, "DISPLAY": "HPEFS" },
{ "VALUE": "NONE", "DISPLAY_ORDER": 3, "DISPLAY": "NONE" }]
}
但有时对于 JSON 中的记录,OPTIONS 为空:
{"FIELD_NAME":"Product_Node3","VALUE":"","FIELD_ID":1740,"OPTIONS":{}}
如您所见,选项设置为 {},但我的理解是 {} 是一个空对象,而不是一个空数组。
当我尝试反序列化为 POCO 时,我收到一个异常,抱怨它需要 OPTIONS 属性中的 JSON 数组。
我的字段类:
public class Field
{
public string FIELD_NAME { get; set; }
public string VALUE { get; set; }
public int FIELD_ID { get; set; }
public List<Option> OPTIONS { get; set;
}
}
和选项类:
public class Option
{
public string VALUE { get; set; }
public int DISPLAY_ORDER { get; set; }
public string DISPLAY { get; set; }
}
导致此异常的代码是:
var stringTest = File.ReadAllText("json.txt");
var data = JsonConvert.DeserializeObject<List<Field>>(stringTest);
例外是:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[testproj.Option]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
【问题讨论】:
-
我相信这对 json.net 来说很好,所以我建议使用它
-
@mjwills - 不完全重复。在那个问题(以及How to handle both a single item and an array for the same property using JSON.net)中,OP 希望将对象反序列化为包含该对象的单项集合。在这里,我相信 OP 想要完全跳过该对象。不过我可能是错的,所以请 OP 确认一下吗?
-
感谢@dbc 的反馈。