2015-11-25 68 views
0

你好我這是通過搜索呼叫得到以下JSON數據GSON:嵌套類擴展

讓這個被稱爲精簡版

{ 
    "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元素更多細節。

看起來像這樣。正如你可以看到有更多的元素。

讓這個被稱爲脂肪

{ 
    "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; 
      } 
} 

然後到發

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擴展內部類?

回答

0

你的Fat類聲明瞭第二個「volumeInfo」。它應該只使用超類字段而不是聲明新字段。

0

從你刪除這兩條線路模型類:

@SerializedName("volumeInfo") 
    private VolInfo mVolInfo; 

不能具有相同名稱的多個屬性。在你的情況volumeInfo屬性爲脂肪類和精簡版

如果你想從你的脂肪類訪問精簡版屬性聲明精簡版與public修改屬性。簡單變量之前更改privatepublic

private VolInfo mVolInfo; 

public VolInfo mVolInfo; 
+0

嗨感謝您的答覆。我如何訪問Fat類中嵌套的VolInfo類,以便訪問這些字段,因爲我現在所能做的就是訪問超類但不是特定於胖子的類 –

+0

@johncarter我編輯了我的答案,您可以將私有變量更改爲在Lite類中公開。只有這樣你纔可以從你的Fat類訪問這些變量 – Arlind

+0

嗨,我已經可以訪問lite了,但我想訪問fat屬性。 –