c# - 将 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# 中的无效名称。
有人可以帮忙吗?谢谢
解决方案
要解决 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=csharp或http://json2csharp.com/以获得先机,然后根据自己的喜好编辑所有内容。
推荐阅读
- node.js - 有没有办法在 nodejs 中的 scp2 上传操作期间公开调试行?
- java - 如何在 Java 中指定文件的路径?
- sql-server - BCP 文件插入命令未恢复 Identity 列的实际值
- android - How to allow only apks those are signed with my platform keys in Android OS
- java - Plotting Logarithmic and Exp graph in Java
- python - 如何将请求和响应“Content-Type”设置为“application/json;charset=UTF-8”?
- amazon-web-services - How to add ec2 instance in aws ecs empty cluster
- google-cloud-ml - 在 google ml 引擎上部署模型时检测到错误模型
- c++ - 在控制台上输出我从文件中读取的整数,使程序陷入无限循环?
- php - Phpspreadsheet - set Hyperlink for cell