Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate the array of json objects(gson)

Tags:

java

json

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?

like image 919
Oyeme Avatar asked Jan 06 '13 13:01

Oyeme


1 Answers

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():
}
like image 148
Perception Avatar answered Oct 22 '22 02:10

Perception