java - 如何将此 Json 对象解析为 Java 对象?
问题描述
我正在尝试将 Json 对象解析为 Java 对象,但我遇到了其中一个键的问题。这是我要解析的关键:
"formats":{"application/x-mobipocket-ebook":"http://www.gutenberg.org/ebooks/84.kindle.images",
"text/plain; charset=utf-8":"http://www.gutenberg.org/files/84/84-0.zip",
"text/html; charset=utf-8":"http://www.gutenberg.org/files/84/84-h/84-h.htm",
"application/rdf+xml":"http://www.gutenberg.org/ebooks/84.rdf",
"application/epub+zip":"http://www.gutenberg.org/ebooks/84.epub.images",
"application/zip":"http://www.gutenberg.org/files/84/84-h.zip",
"image/jpeg":"http://www.gutenberg.org/cache/epub/84/pg84.cover.small.jpg"}
所以我有这样的Java类:
public class Format {
@JsonProperty("application/x-mobipocket-ebook")
private String ebook;
@JsonProperty("text/plain; charset=utf-8")
private String textPlain;
@JsonProperty("text/html; charset=utf-8")
private String textHtml;
@JsonProperty("application/rdf+xml")
private String textXml;
@JsonProperty("application/epub+zip")
private String epubZip;
@JsonProperty("application/zip")
private String zip;
@JsonProperty("image/jpeg")
private String image;
//getters, setters and toString..
}
我得到了其他键的结果(它只是一个带有名称、作者等的 json 对象),但使用这个键我得到了 null。那我怎么能正确地得到这些信息呢?(我现在已经找了一段时间,但其他答案没有用)
解决方案
您可以使用 @SerializedName 注释。此注解指示应将注解的成员序列化为 JSON,并将提供的名称值作为其字段名称。
原始/formats_sample.json
{
"formats":{
"application/x-mobipocket-ebook":"http://www.gutenberg.org/ebooks/84.kindle.images",
"text/plain; charset=utf-8":"http://www.gutenberg.org/files/84/84-0.zip",
"text/html; charset=utf-8":"http://www.gutenberg.org/files/84/84-h/84-h.htm",
"application/rdf+xml":"http://www.gutenberg.org/ebooks/84.rdf",
"application/epub+zip":"http://www.gutenberg.org/ebooks/84.epub.images",
"application/zip":"http://www.gutenberg.org/files/84/84-h.zip",
"image/jpeg":"http://www.gutenberg.org/cache/epub/84/pg84.cover.small.jpg"
}
}
然后在 Format 类中,在您的属性中添加 SerializedName 注释
class Format {
@SerializedName("application/x-mobipocket-ebook")
private String ebook;
@SerializedName("text/plain; charset=utf-8")
private String textPlain;
@SerializedName("text/html; charset=utf-8")
private String textHtml;
@SerializedName("application/rdf+xml")
private String textXml;
@SerializedName("application/epub+zip")
private String epubZip;
@SerializedName("application/zip")
private String zip;
@SerializedName("image/jpeg")
private String image;
//getters, setters and toString..
}
就是这样,玩得开心!
gson.fromJson(FileUtils.loadFromRaw(context, R.raw.formats_sample), Format::class)
推荐阅读
- mesh - Raycast Mesh 的所有面
- java - 如何等到文件被下载或在所需文件夹中可用?
- python - 组合 Seaborn 线 + 条形图时的 X 轴问题
- r - 总结 R 中几个网络的中心性统计
- jquery - 如何转换 JSON 中的所有数据表记录?
- python - 如何在刻度标签中心的 sns.heatmap 上绘制线图
- c# - 如何使用 C# 和 OpenXml 读取 docx 文件的表格单元格中的合并字段内容
- kotlin - Kotlin/Fuel - 未解决的参考:使用应用时的 responseString
- c++ - 柯南包从官方仓库迁移到本地私有仓库
- scheme - Scheme中过滤高阶函数