【发布时间】:2019-03-07 20:14:58
【问题描述】:
我正在尝试使用 Newtonsoft.Json 组件在 C# 中解析 JSON。我得到的 JSON 是这样的:
[
{
"id": "2",
"title": "First Title",
"image": "550x346_442.jpg",
"audio": null,
"order": "3",
"schedule": {
"4": [
"17:00",
"17:30"
]
}
},
{
"id": "3",
"title": "Second Title",
"image": "myImage.jpg",
"audio": null,
"order": "4",
"schedule": {
"4": [
"17:00",
"18:00",
"19:30"
],
"6": [
"17:30",
"21:30"
]
}
},
]
我有一堂课,但所有的课程都可以解析。我不知道 schedule 字段使用什么类型。我尝试了 string[]、string[,] 和 string[][],但总是出错。也试过刚才的字符串类型,然后尝试重新解析,也失败了。每个其他字段都被解析为字符串类型并且工作正常。我是这样解析的:
MyClass[] myObjects = JsonConvert.DeserializeObject<MyClass[]>(jsonStr);
我应该使用什么类型的日程安排?
【问题讨论】:
-
您可以将
schedule声明为public Dictionary<string, List<string>> schedule { get; set; },如Deserializing JSON when key values are unknown 或Deserializing JSON with unknown object names 或Create a strongly typed c# object from json object with ID as the name 或Parsing JSON Object with variable properties into strongly typed object 所示。事实上,我认为这是重复的,同意吗? -
我不认为这个问题是重复的(可能是重复的,我看不到),但它的答案似乎很合适。让我深入尝试以获得完整的答案!谢谢!
-
正确的答案是 public Dictionary
,非常接近你的建议!您的解决方案也有效,但 string[] 更准确。如果你愿意,你可以把它写下来作为答案,我会选择它作为正确的答案,因为它是你所说的 98%! :)