以数字为键反序列化JSON [英] Deserializing JSON with numbers as keys

查看:202
本文介绍了以数字为键反序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了如何获取每个键,现在问题是遍历每个集合.底部的解决方案!

我正在尝试解析具有以下格式的JSON有效负载:

I'm trying to parse a JSON payload that has the following format:

{
    "version": "1.1", 
    "0": {
              "artist": "Artist 1",
              "title": "Title 1"
         },
    "1": {
              "artist": "Artist 2",
              "title": "Title 2"
         },
    ...
    "29": {
              "artist": "Artist 30",
              "title": "Title 30"
         }
}

我不需要version键,因此在编写类时忽略了它.这是我到目前为止的内容:

I don't need the version key, so I'm ignoring it while coding my classes. This is what I have so far:

public class Song
{
    public string artist { get; set; }
    public string title { get; set; }
}

我已经检查过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!

Dictionary<int, Dictionary<string, string>> song = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<string, string>>>(json);

我可以通过以下方式访问artisttitle属性:

And I can access the artist and title properties via:

song[0]["artist"]
song[0]["title"]

分别.

这消除了对预构建类的需求.现在,我在遍历每组数据时都遇到麻烦(例如,歌曲[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<int, Dictionary<string, string>>,您将遇到version键的问题,因为它不适合字典的数据格式(version不是int1.1不是Dictionary<string, string>).我知道您说过您现在暂时忽略它",但这意味着它会在将来出现,因此您需要处理它.

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的

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:

class Program
{
    static void Main(string[] args)
    {
        string 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""
                 }
        }";

        JObject songs = JObject.Parse(json);

        foreach (JProperty song in songs.Properties())
        {
            if (song.Name == "version") continue;  // skip "version" property
            Console.WriteLine("Song " + song.Name + " artist: " + song.Value["artist"]);
            Console.WriteLine("Song " + song.Name + " title: " + song.Value["title"]);
        }
    }
}

输出:

Song 0 artist: Artist 1
Song 0 title: Title 1
Song 1 artist: Artist 2
Song 1 title: Title 2
Song 29 artist: Artist 30
Song 29 title: Title 30

文档中可以找到许多其他示例

.

这篇关于以数字为键反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆