2013-01-06 11 views
5

Sto realizzando un gioco di difesa navale.
Ho un problema con l'acquisizione della matrice di waypoint. La mappa contiene il formato JSON (Usando GSON)Come eseguire l'iterazione dell'array di oggetti 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]]        
    } 
    } 
} 

Il mio codice:

jse = new JsonParser().parse(in); 
    in.close(); 

    map_json = jse.getAsJsonObject(); 
    JsonObject wayPoints = map_json.getAsJsonObject("waypoints").getAsJsonObject("ship"); 

ho scritto questo, ma non funziona.

JsonArray asJsonArray = wayPoints.getAsJsonObject().getAsJsonArray(); 

Come posso impostare l'array di oggetti?

risposta

15

È possibile semplificare il codice e recuperare l'array first_type utilizzando il seguente codice. Lo stesso codice dovrebbe funzionare anche per l'array second_type:

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

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

wayPoints è un oggetto JSON. Contiene un altro oggetto JSON chiamato ship. E ship contiene un array JSON chiamato first_type. Quindi dovresti ottenere l'array first_type dall'oggetto ship e iterare su questo array.

Problemi correlati