1

This is a follow on from Dealing with fanart.tv webservice response JSON and C#

So for artists you get a response where the main element is named the same as the artist (hence you call the webservice for thumbs for Metallica the root it called Metallica, you call it for Megadeth is is called Megadeth)

The previous question resolves that but the next stage down is albums which ends up containing two levels of these dynamically named elements so searching for a particular album and you get

{"Metallica":{"mbid_id":"65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab","albums":{"f44f4f73-a714-31a1-a4b8-bfcaaf311f50":{"albumcover":[{"id":"51252","url":"http://assets.fanart.tv/fanart/music/65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab/albumcover/kill-em-all-504c485914b25.jpg","likes":"2"}]}}}}

So you have the same top level artist details with the dynamic name but now you have for albums you have an element which is named after the MusicbrainzID and then the collection of thumbs.

For the artist details I defined classes

public class ArtistThumbs
{
  public string Name { get; set; }

  [JsonProperty("mbid_id")]
  public string MusicBrainzID { get; set; }

  [JsonProperty("artistthumb")]
  public List<Thumb> Thumbs { get; set; }
}

and

public class Thumb
{
  [JsonProperty("id")]
  public string Id { get; set; }

  [JsonProperty("url")]
  public string Url { get; set; }

  [JsonProperty("likes")]
  public string Likes { get; set; }
}

Then I can just de-serialize the artist to JSON with

var artistthumbs = JsonConvert.DeserializeObject<Dictionary<string, Artist>>(json);

question is how can I do the same for these albums? I really need to try and stick with JsonConvert.DeserializeObject if possible and really want to de-serialize to classes but I can't figure out how to model the classes

Community
  • 1
  • 1
Jameson_uk
  • 432
  • 2
  • 12
  • Kindly refer the following post http://stackoverflow.com/questions/17488257/c-sharp-object-to-json-convert/17501301#17501301 – captainsac Jul 06 '13 at 11:35

1 Answers1

1

Same idea as the other question. Whenever you have dynamically changing property names for a JSON object you need to use a Dictionary. You can extend your existing classes easily enough to handle this.

First, define another class to hold the list of cover thumbs for the album:

class Album
{
    [JsonProperty("albumcover")]
    public List<Thumb> CoverThumbs { get; set; }
}

Then add the following to your property to your ArtistThumbs class:

[JsonProperty("albums")]
public Dictionary<string, Album> Albums { get; set; }

Then you can deserialize exactly as you have been doing:

var artistthumbs = JsonConvert.DeserializeObject<Dictionary<string, ArtistThumbs>>(json);

The Albums property now has the albums, where each key in the dictionary is the "MusicbrainzID" for the album and each value is the corresponding Album info.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300