使用Gson解析复杂的嵌套JSON数据

时间:2015-05-31 15:19:47

标签: java json object nested gson

我正在使用Gson解析JSON字符串。我想使用容器类和嵌入的静态类将其转换为对象。在某种程度上这是可能的,但我想将stuff1stuff2的内容视为数组,例如,stuff1是一个包含other_stuff1和{{{ 1}}。这样我就可以像这样的方式引用对象:other_stuff2object.integerobject.stuff1.get("other_stuff1").name。 (对于最后一个,我可能有兴趣循环object.stuff2.get("other_stuff3").more来获取每个项目。

例如,在PHP中,我会使用它:

more

我希望能够以类似的方式引用,将JSON加载到要在运行中使用的对象。

至关重要的是,尽管可以对JSON进行一定程度的更改,但元素的名称仍然存在并且可以被检索和检索。

我已经加入了JSON,与我以下使用的JSON非常相似。

<?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.
    }
?>

我已经阅读了许多参考指南和教程,但我无法找到一种方法来解释这种方式。

如果有人能给我指针,我真的很感激。我无法找到任何考虑到以下内容的教程:a)我想要数组样式列表中的多个对象,可以通过ID引用(例如{ "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" } } }, } } other_stuff1),以及b)我希望能够在不提供ID的情况下循环遍历项目。

1 个答案:

答案 0 :(得分: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());
}