首页 > 解决方案 > 将 iTunes 商店中的 Json 反序列化为 C# 对象

问题描述

我从 iTunes 返回了以下 Json(我已经替换了一些隐私细节,例如用户名和评论内容)

{"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 ... 

我想把它反序列化成一个类。我只需要评论标题、评论内容和“im:rating”(即星数)。但是,由于嵌套的 Json 和使用如何提取此数据的键,我正在苦苦挣扎。到目前为止,我已经创建了一个准备反序列化的类,我必须AppStoreData appStoreData = JsonConvert.DeserializeObject<AppStoreData>(stringResult);反序列化它

public class AppStoreData {

}

我的问题是我不知道在课堂上放什么来从 Json 获取我需要的信息。我尝试过诸如:

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

但是,这不起作用。我也认为im:rating是 C# 中的无效名称。

有人可以帮忙吗?谢谢

标签: c#.netjsonapiapp-store

解决方案


要解决 im:rating 的问题,您可以使用 JsonProperty 属性

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

将 Label 转换为字符串属性的问题在于它不是字符串,而是输入文件中的对象。你需要类似的东西

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

其中 Id 是一个类

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

或者编写一个反序列化器,为您将其转换为字符串。

我建议尝试使用许多免费的代码生成器之一,例如https://app.quicktype.io/?l=csharphttp://json2csharp.com/以获得先机,然后根据自己的喜好编辑所有内容。


推荐阅读