Oyeme
Oyeme

Reputation: 11225

How to Iterate the array of json objects(gson)

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)

{
 "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?

Upvotes: 7

Views: 15685

Answers (2)

Perception
Perception

Reputation: 80603

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:

JsonArray types = map_json
    .getAsJsonObject("waypoints")
    .getAsJsonObject("ship")
    .getAsJsonArray("first_type";

for(final JsonElement type : types) {
    final JsonArray coords = type.getAsJsonArray():
}

Upvotes: 18

JB Nizet
JB Nizet

Reputation: 691705

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.

Upvotes: 2

Related Questions