问题描述
我想出了如何获取每个键,现在问题是循环遍历每个集合.底部的解决方案!
我正在尝试解析具有以下格式的 JSON 有效负载:
I'm trying to parse a JSON payload that has the following format:
我不需要 version
键,所以我在编写课程时忽略了它.这是我目前所拥有的:
I don't need the version
key, so I'm ignoring it while coding my classes. This is what I have so far:
我检查了 StackOverflow,看到有人使用 Dictionary<int, string>
解决类似问题,但看起来人们在根目录中没有每个 JSON 对象.我正在使用 JSON.net 来解析所有内容.
I've checked around StackOverflow and I've seen people using Dictionary<int, string>
for similar problems, but it doesn't look like people have each JSON object in the root. I'm using JSON.net to parse everything.
在 PHP 中,我可以轻松地使用 json_decode()
并遍历数组并提取我需要的所有信息,但我被 C# 难住了.
In PHP, I could easily use json_decode()
and walk through the array and extract all the info I need, but I'm stumped by C#.
解决方案从下面开始.
我查看了 JSON.net 文档,他们使用字典,所以我尝试使用嵌套字典,它似乎工作!
I looked at the JSON.net documentation and they used dictionaries, so I tried using nested dictionaries, and it seems to work!
我可以通过以下方式访问 artist
和 title
属性:
And I can access the artist
and title
properties via:
分别.
这消除了对预构建类的需要.现在,我无法循环遍历每组数据集合(例如歌曲 [1]、歌曲 [2]、歌曲 [3]、...、歌曲 [n] 的艺术家和标题信息).
This eliminates the need for pre-built classes. Now I'm having trouble looping through each set of data collection (e.g. artist and title info for song[1], song[2], song[3], ..., song[n]).
推荐答案
如果你尝试用上面的 JSON 反序列化成 Dictionary
version
键会遇到问题,因为它不适合字典的数据格式(version
不是 int
,并且 1.1
不是 Dictionary
).我知道你说你暂时忽略它",但这意味着它将来会在那里,所以你需要处理它.
If you try to deserialize into a Dictionary<int, Dictionary<string, string>>
with the above JSON you're going to run into problems with the version
key because it does not fit the data format for the dictionaries (version
is not an int
, and 1.1
is not a Dictionary<string, string>
). I know you said you're "ignoring it for now", but that implies that it will be there in the future, so you need to handle it.
如果你不想有预定义的类,那么你最好使用 Json.Net 的 LINQ-to-JSON API 来处理数据.以下是使用这种方法获取所需数据的方法:
If you don't want to have pre-defined classes, then you're better off using Json.Net's LINQ-to-JSON API to work with the data. Here is how you can get the data you want using this approach:
输出:
文档.
这篇关于以数字为键反序列化 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!