[英]Parsing complex nested JSON data with Gson
我正在使用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,与我正在使用的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
(而不是数组)来获取您描述的.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"
字段,您需要使用不同的变量名称,因为boolean
是保留关键字。
然后你可以这样做:
Container c = gson.fromJson(jsonString, Container.class);
for(Stuff s : c.getStuff1().values()) {
System.out.println(s.getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.