编辑:我想出了如何获得每个键,现在问题是循环每个集合.底部解决方案!
我正在尝试解析具有以下格式的JSON有效内容:
{
"version": "1.1",
"0": {
"artist": "Artist 1",
"title": "Title 1"
},
"1": {
"artist": "Artist 2",
"title": "Title 2"
},
...
"29": {
"artist": "Artist 30",
"title": "Title 30"
}
}
Run Code Online (Sandbox Code Playgroud)
我不需要version密钥,因此我在编写类时忽略它.这是我到目前为止:
public class Song
{
public string artist { get; set; }
public string title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我已经检查了StackOverflow并且我看到人们使用Dictionary<int, string>类似的问题,但它看起来并不像人们在根中拥有每个JSON对象.我正在使用JSON.net来解析所有内容.
在PHP中,我可以轻松地使用json_decode()和遍历数组并提取我需要的所有信息,但我被C#难倒.
编辑:解决方案从下面开始.
我查看了JSON.net文档,他们使用了字典,所以我尝试使用嵌套字典,它似乎工作!
Dictionary<int, Dictionary<string, string>> song = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<string, string>>>(json);
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式访问artist和title属性:
song[0]["artist"]
song[0]["title"] …Run Code Online (Sandbox Code Playgroud)