SebastianOS
SebastianOS

Reputation: 55

Dynamic keys in JSON

First of all I'm not sure if "dynamic key" is the correct term, but my problem is the following one.

current json:

{
  "Entered": "2012-08-18T13:26:37.7137482-10:00",
  "AlbumName": "Dirty Deeds Done Dirt Cheap",
  "Artist": "AC/DC",
  "YearReleased": 1976,
  "Songs": [
    {
      "SongName": "Dirty Deeds Done Dirt Cheap",
      "SongLength": "4:11"
    },
    {
      "SongName": "Love at First Feel",
      "SongLength": "3:10"
    }
  ]
}

the new one:

{
  "Entered": "2012-08-18T13:26:37.7137482-10:00",
  "AlbumName": "Dirty Deeds Done Dirt Cheap",
  "Artist": "AC/DC",
  "YearReleased": 1976,
  "Songs": {
    "Dirty Deeds Done Dirt Cheap": {
                                    "SongLength": "4:11"
                                   },
    "Love at First Feel": {
                           "SongLength": "3:10"
                          }
  }
}

My question is how should the Model looks like and how can I change the key name dynamically?

public class CD
    {
        public DateTime Entered { get; set; }
        public string AlbumName { get; set; }
        public string Artist { get; set; }
        public int YearReleased { get; set; }
        public List<Song> Songs { get; set; }
    }
public class Song
    {
        public string Name {get;set;}
        public string Length {get;set;}
    }

Upvotes: 1

Views: 101

Answers (1)

Maytham Fahmi
Maytham Fahmi

Reputation: 33437

For your new json format you need to change data structure to Dictionary.

So instead of list:

public List<Song> Songs { get; set; }

Change to

public Dictionary<string, Song> Songs { get; set; }

I assume your keys are unique.

I have tested this and it works.

Upvotes: 1

Related Questions