我试图将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对象),但是这个键没有问题,我得到的结果是空的。那么,我如何才能正确地获取这些信息呢?(我已经找了一段时间了,但其他答案都不起作用)
发布于 2021-01-03 04:20:08
您可以使用@SerializedName注释。该注释指示带注释的成员应该被序列化为JSON,并使用提供的name值作为其字段名。
raw/format_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)https://stackoverflow.com/questions/65543057
复制相似问题