Deserializing JSON with numbers as keys

前端 未结 1 478
执笔经年
执笔经年 2020-12-07 02:18

EDIT: I figured out how to get each key, now the problem is looping through each collection. Solution at bottom!

I\'m trying to parse a JSON payload

相关标签:
1条回答
  • 2020-12-07 02:44

    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.

    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"]);
            }
        }
    }
    

    Output:

    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
    

    There are many other samples to be found in the documentation.

    0 讨论(0)
提交回复
热议问题