java 如何迭代json对象数组(gson)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14182511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Iterate the array of json objects(gson)
提问by Oyeme
I'm making a ship defense game.
I have a problem with getting the array of waypoints.
The map contains the JSON
format(Using GSON
)
我正在制作一个船舶防御游戏。
我在获取航点数组时遇到问题。地图包含JSON
格式(使用GSON
)
{
"waypoints" : {
"ship": {
"first_type": [[0,0],[5,7],[2,8],[4,4],[10,10],[12,0],[0,12],[12,8],[8,8]]
},
"boat": {
"first_type": [[0,0],[5,7],[2,8],[4,4],[10,10],[12,0],[0,12],[12,8],[8,8]]
}
}
}
My code:
我的代码:
jse = new JsonParser().parse(in);
in.close();
map_json = jse.getAsJsonObject();
JsonObject wayPoints = map_json.getAsJsonObject("waypoints").getAsJsonObject("ship");
I wrote this one,but it doesn't work.
我写了这个,但它不起作用。
JsonArray asJsonArray = wayPoints.getAsJsonObject().getAsJsonArray();
How can I foreach the array of objects?
我怎样才能 foreach 对象数组?
回答by Perception
You can simplify your code and retrieve the first_type
array using the following code. Same code should pretty much work for the second_type
array as well:
您可以first_type
使用以下代码简化代码并检索数组。相同的代码也应该适用于second_type
数组:
JsonArray types = map_json
.getAsJsonObject("waypoints")
.getAsJsonObject("ship")
.getAsJsonArray("first_type";
for(final JsonElement type : types) {
final JsonArray coords = type.getAsJsonArray():
}
回答by JB Nizet
wayPoints
is a JSON object. It contains another JSON object called ship
. And ship
contains a JSON array called first_type
. So you should get the first_type
array from the ship
object, and iterate on this array.
wayPoints
是一个 JSON 对象。它包含另一个名为 的 JSON 对象ship
。并ship
包含一个名为 .json 的 JSON 数组first_type
。所以你应该first_type
从ship
对象中获取数组,并迭代这个数组。