我正在使用 Gson 来解析 JSON 字符串。我想使用容器类和嵌入式静态类将其转换为对象。在某种程度上这已经成为可能,但是我想把stuff1
和stuff2
的内容当作数组,比如stuff1
就是一个数组包含 other_stuff1
和 other_stuff2
。这样我就可以像这样引用对象:object.integer
、object.stuff1.get("other_stuff1").name
或 object .stuff2.get("other_stuff3").more
。 (对于最后一个,我可能有兴趣循环遍历 more
来获取每个项目。
例如,在 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_stuff1
和 other_stuff2
) , 和 b) 我还希望能够在不提供 ID 的情况下遍历项目。
最佳答案
您应该定义一个 Java 类,其中包含以您需要的键命名的字段。您可以使用 Map
s (不是数组)来获取您描述的 .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());
}
关于java - 使用 Gson 解析复杂的嵌套 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559067/