【发布时间】:2017-11-27 15:21:23
【问题描述】:
我从这里的一个类似问题中拿了这个例子:
Iterating over a JSON object (NOT an array) in C#
但我的数据格式有点不同,它有数组括号。
正如所指出的,我可以有未定义数量的条目,我想遍历条目并根据定义的类将数据结构提取到对象数组/列表中。
{
"-KeArK3V02mXYWx2OMWh" : [{
"Description" : "this is a description",
"Location" : "Atlanta",
"Name" : "Event One",
"Time" : "2017-03-01T21:53:12.924645Z"
}],
"-KeAtCNF_rmewZ_U3PpH" : [{
"Description" : "another description",
"Location" : "Charlotte",
"Name" : "Event Two",
"Time" : "2017-03-01T22:01:25.603547Z"
}],
"-KeAtd8CQW_EfH3Sw4YQ" : [{
"Description" : "description goes here",
"Location" : "Toronto",
"Name" : "Event Three",
"Time" : "2017-03-01T22:03:19.3953859Z"
}]
}
我有一个名为 Event 的类,其定义如下
class Title {
public string Description { get; set; }
public string Location { get; set; }
public string Name { get; set; }
public DateTime Time { get; set; }
}
那里给出的答案(我认为是正确的)不起作用
Dictionary<string, Title> elist = JsonConvert.DeserializeObject<Dictionary<string, Title>>(jsonString);
它给了我一个错误:
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“Title”,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。 JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组反序列化。 路径“-KeArK3V02mXYWx2OMWh”,第 2 行,位置 XX。
【问题讨论】:
标签: c# arrays json dynamic undefined