2013-01-06 96 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阵列,并反复在这个阵列上。