【发布时间】:2015-05-31 15:19:46
【问题描述】:
我正在使用 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 json object nested gson