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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:23:43  来源:igfitidea点击:

How to Iterate the array of json objects(gson)

javajsongson

提问by Oyeme

I'm making a ship defense game.
I have a problem with getting the array of waypoints. The map contains the JSONformat(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_typearray using the following code. Same code should pretty much work for the second_typearray 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

wayPointsis a JSON object. It contains another JSON object called ship. And shipcontains a JSON array called first_type. So you should get the first_typearray from the shipobject, and iterate on this array.

wayPoints是一个 JSON 对象。它包含另一个名为 的 JSON 对象ship。并ship包含一个名为 .json 的 JSON 数组first_type。所以你应该first_typeship对象中获取数组,并迭代这个数组。