2013-01-06 51 views
5

我做一艘船防禦遊戲的陣列。
我有越來越航點的陣列的一個問題。 地圖包含JSON格式(使用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]]        
    } 
    } 
} 

我的代碼:

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

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

我寫了這一個,但它不工作。

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

如何可以foreach對象數組?

回答

15

您可以簡化您的代碼,並使用下面的代碼檢索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

wayPoints是JSON對象。它包含另一個名爲ship的JSON對象。並且ship包含一個名爲first_type的JSON數組。所以,你應該從ship對象first_type陣列,並反覆在這個陣列上。