如何迭代json对象数组(gson)

时间:2022-02-19 16:46:41

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?

我如何预测对象数组?

2 个解决方案

#1


15  

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():
}

#2


2  

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对象。它包含另一个名为ship的JSON对象。并且ship包含一个名为first_type的JSON数组。所以你应该从ship对象中获取first_type数组,并迭代这个数组。

#1


15  

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():
}

#2


2  

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对象。它包含另一个名为ship的JSON对象。并且ship包含一个名为first_type的JSON数组。所以你应该从ship对象中获取first_type数组,并迭代这个数组。