Search code examples
c#json.netapp-store

Deserializing JSON from iTunes store into C# object


I have the following Json returned from iTunes (I have replaced some details for privacy such as username and review content):

{"feed":{"author":{"name":{"label":"iTunes Store"}, "uri":{"label":"http://www.apple.com/uk/itunes/"}}, "entry":[
{"author":{"uri":{"label":"https://itunes.apple.com/gb/reviews/ID"}, "name":{"label":"Username"}, "label":""}, "im:version":{"label":"3.51"}, "im:rating":{"label":"4"}, "id":{"label":"12345"}, "title":{"label":"Review title"}, "content":{"label":"Review contents", "attributes":{"type":"text"}}, "link":{"attributes":{"rel":"related", "href":"https://itunes.apple.com/gb/review?reviewid"}}, "im:voteSum":{"label":"0"}, "im:contentType":{"attributes":{"term":"Application", "label":"Application"}}, "im:voteCount":{"label":"0"}}, 

// more entries ... 

I want to deserialize this into a class. I only need the Review Title, Review contents, and the "im:rating" (which is the number of stars). However, I'm struggling due to the nested Json and the use of keys of how to extract this data. So far I have created a class ready to deserialize, and I have AppStoreData appStoreData = JsonConvert.DeserializeObject<AppStoreData>(stringResult); to deserialize it

public class AppStoreData {

}

My problem is that I don't know what to put inside the class to get the info I need from the Json. I have tried things such as:

public string title {get; set;} public string content {get; set;} public string imrating {get; set;}

However this doesn't work. I also think im:rating is an invalid name in C#.

Can anyone please help?


Solution

  • To get around the issue with im:rating you can use a JsonProperty attribute

        [JsonProperty("im:rating")]
        public Id ImRating { get; set; }
    

    The issue with converting things like Label to string property is that it's not a string but an object in the input file. You need something like

         [JsonProperty("title")]
         public Id Title { get; set; }
    

    where Id is a class

    public class Id
    {
        [JsonProperty("label")]
        public string Label { get; set; }
    }
    

    Or write a deserializer that converts it to string for you.

    I would suggest trying out one of many free code generators like https://app.quicktype.io/?l=csharp or http://json2csharp.com/ to get a headstart and edit everything to your liking afterwards.