GSON:嵌套类扩展

时间:2015-11-25 22:02:40

标签: java gson

您好我获得了以下通过搜索电话

获得的JSON数据

将其称为精简版

{
  "selfLink": "https://www.googleapis.com/books/v1/volumes/8MlZPgAACAAJ",
 "id": "8MlZPgAACAAJ",
  "volumeInfo": {
    "title": "Harry Potter Textbook Box Set",
    "authors": [
      "J. K. Rowling"
    ],
    "publisher": "Scholastic",
    "publishedDate": "2001-11-01",

  }
}

在数据中有一个selfLink元素,可以带您了解更多细节。

哪个看起来像这样。如您所见,有更多元素。

将其称为 Fat

{
  "selfLink": "https://www.googleapis.com/books/v1/volumes/8MlZPgAACAAJ",
  "id": "8MlZPgAACAAJ",
  "volumeInfo": {
    "title": "Harry Potter Textbook Box Set",
    "authors": [
      "J. K. Rowling"
    ],
    "publisher": "Scholastic",
    "publishedDate": "2001-11-01",
    "description": "Presents facsimile editions of two books from the world of Harry Potter--the text for Hogwarts' Care of Magical Creatures class and a book on the origins and development of the wizarding game of Quidditch.",
    "printType": "BOOK",
    "categories": [
      "Juvenile Fiction / Fantasy & Magic"
    ],
    "language": "en",
    "previewLink": "http://books.google.co.uk/books?id=8MlZPgAACAAJ&hl=&source=gbs_api",
    "infoLink": "http://books.google.co.uk/books?id=8MlZPgAACAAJ&hl=&source=gbs_api",
    "canonicalVolumeLink": "http://books.google.co.uk/books/about/Harry_Potter_Textbook_Box_Set.html?hl=&id=8MlZPgAACAAJ"
  }
}

此类模拟精简版

        public class Lite{
            @SerializedName("selfLink")
            private String mSelfLink;

            @SerializedName("volumeInfo")
            private VolInfo mVolInfo;

        public static class VolInfo {
            @SerializedName("title")
            private String mTitle;

            @SerializedName("publishedDate")
            private String mPublishedDate;

            @SerializedName("authors")
            private String[] mAuthors;

            @SerializedName("publishedDate")
            private String mPublishedDate;
            }
}

然后模拟Fat

public class Fat extends Lite{

@SerialisedName("id")
private String mId;

  @SerializedName("volumeInfo")
  private VolInfo mVolInfo;


 public static class VolInfo extends Lite.VolInfo {
       // The other elements that is in the fat call
}

}

但问题是我收到此错误

  

java.lang.IllegalArgumentException:声明多个JSON字段   命名为volumeInfo

那么可以在GSON中扩展内部类吗?

2 个答案:

答案 0 :(得分:0)

你的Fat类声明了第二个“volumeInfo”。它应该只使用超类字段而不是声明一个新字段。

答案 1 :(得分:0)

Fat 模型类:

中删除这两行
  @SerializedName("volumeInfo")
  private VolInfo mVolInfo;

您不能拥有多个具有相同名称的属性。在您的情况下,volumeInfo属性位于 Fat 类和 Lite

如果要从 Fat 类访问 Lite 属性,请使用public修饰符声明Lite属性。只需在变量之前将private更改为public

private VolInfo mVolInfo;

public VolInfo mVolInfo;