2015-05-31 85 views
1

我使用Gson來解析JSON字符串。我想使用容器類和嵌入靜態類將其轉換爲對象。在某種程度上這是可能的,但我想將stuff1stuff2的內容當作數組來處理,例如,stuff1是包含other_stuff1other_stuff2的數組。這樣我就可以像這樣的方式引用對象:object.integer,object.stuff1.get("other_stuff1").nameobject.stuff2.get("other_stuff3").more。 (最後一個,我會很感興趣的遍歷more獲得每個項目使用Gson解析複雜的嵌套JSON數據

例如,在PHP中,我會用這樣的:

<?php 
    echo "<pre>"; 
    $object = json_decode(file_get_contents("THE JSON FILENAME")); 
    foreach($object->stuff1 as $name=>$data) { 
     echo $name . ":\n"; // other_stuff1 or other_stuff2 
     echo $unlockable->description . "\n\n"; // Got lots of stuff or Got even more stuff. 
    } 
?> 

我希望能夠在一個參考類似的方法,將JSON加載到要動態使用的對象

儘管JSON可以進行某種程度的更改,但是元素的名稱仍然存在並且可供參考和檢索,這一點至關重要。

我已經包含了JSON,非常相似到我正在使用的下面。

{ 
    "integer":"12345", 
    "stuff1":{ 
     "other_stuff1":{ 
      "name":"a_name", 
      "description":"Got lots of stuff.", 
      "boolean":false 
     }, 
     "other_stuff2":{ 
      "name":"another_name", 
      "description":"Got even more stuff", 
      "boolean":true 
     } 
    }, 
    "stuff2":{ 
     "other_stuff3":{ 
      "name":"a_name", 
      "description":"Got even more stuff", 
      "boolean":false, 
      "more":{ 
       "option1":{ 
        "name":"hello" 
       }, 
       "option2":{ 
        "name":"goodbye" 
       } 
      } 
     }, 
    } 
} 

我已經通過了一些參考指南和教程走了,我無法找到一個方法來解釋這個我想的方式。

我真的很感激,如果有人能給我一個指針。我找不到任何教程考慮到a)我想要一個數組樣式列表中的多個對象,可以通過ID參考(例如使用other_stuff1other_stuff2),以及b)我還希望能夠遍歷項目不提供ID。

回答

3

您應該定義一個Java類,其中的字段以您需要的鍵名命名。您可以使用Map(不是陣列)來獲取您描述的.get("key")行爲。例如:

class Container { 
    private final int integer; 
    private final HashMap<String, Stuff> stuff1; 
    private final HashMap<String, Stuff> stuff2; 
} 

class Stuff { 
    private final String name; 
    private final String description; 
    @SerializedName("boolean") private final boolean bool; 
    private final HashMap<String, Option> more; 
} 

class Option { 
    private final String name; 
} 

對於"boolean"領域,你需要需要use a different variable name,因爲boolean是保留關鍵字。

那麼你可以這樣做:

Container c = gson.fromJson(jsonString, Container.class); 
for(Stuff s : c.getStuff1().values()) { 
    System.out.println(s.getName()); 
} 
+0

它不應該是足夠的聲明在集裝箱領域爲'Map',而不是'HashMap'? – ralfstx

+1

@ralfstx一個快速測試表明,如果您指定'Map​​',Gson將生成一個[''com.google.gson.internal.LinkedTreeMap'](https://github.com/google/gson/blob/master/gson/src /main/java/com/google/gson/internal/LinkedTreeMap.java)。有一個['LinkedHashTreeMap'](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/LinkedHashTreeMap.java)有時可能會返回。最好明確你想要的類型(例如'HashMap','LinkedHashMap'等),但如果你只是指定'Map​​'作爲所需的類型,Gson將使用合理的默認值。 – dimo414

+0

這些映射實現在迭代時保持元素的原始順序,這可能是需要的。 'HashMap'是'Map'接口的流行實現,但對於'Container'類型的用戶來說,這個實現是無關緊要的。 – ralfstx