2015-05-31 86 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