首页 > 解决方案 > 如何将此 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。那我怎么能正确地得到这些信息呢?(我现在已经找了一段时间,但其他答案没有用)

标签: javaandroidjson

解决方案


您可以使用 @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)

推荐阅读