0

我将解析一个从 web 服务器到 android 应用程序的 json 数组。数组看起来像这样

{"Level":
         [
         {"route":[{"lat":38.889762,"lgn":-77.081764},
         {"lat":38.89096,"lgn":-77.081916}]}, 
         {"route":[{"lat":38.889762,"lgn":-77.081764},
         {"lat":38.89096,"lgn":-77.081916}]},
         {"route":[{"lat":38.889762,"lgn":-77.081764},
         {"lat":38.89096,"lgn":-77.081916}]}
         ]
}

我的java代码是

        JSONObject json = new JSONObject(result);
    JSONArray jArray = json.getJSONArray("Level");
    rlevel = new ArrayList<LatLng>();
    System.out.println("*****JARRAY*****"+jArray.length());

    for(int i=0;i<jArray.length();i++){


     JSONObject json_data = jArray.getJSONObject(i);

     jlat = json_data.getDouble("lat");
     jlgn = json_data.getDouble("lgn");}

但不起作用!有什么想法吗?在此之后我想将每条路线保存到一个数组中(等 $plan[1]=来自 json 的第一条路线,$plan[2]=来自 json 的第二条路线)

4

2 回答 2

0

尝试这样的事情:

//code 是您保存 json 的字符串

JSonObject json= new JsonParser().parse(code).getAsJsonObject();
JsonArray jArray= json.getAsJsonArray("Level");
rLevel=new ArrayList<LatLng>();

//notice the use of the size() method. There is not length() method defined for ArrayList
System.out.println("*****JARRAY*****"+jArray.size());

for(int i=0;i<jArray.size();i++){

//notice that inside the Level Array you have route-arrays
    JSonObject level_item = jArray.get(i).getAsJsonObject();
    JSonArray route= level_item.getAsJSonArray("route");

//now I don't know exactly what data you want to extract, since there are 2
//pairs of LatLng, for the first one:
jlat = route.get(0).get("lat").getAsDouble();
jlgn= route.get(0).get("lgn").getASDouble();

方法和 JsonObjects 的确切名称往往因库而异,但原理是相同的。

于 2013-07-29T00:50:19.573 回答
0

使用droidQuery可以非常轻松地完成此解析任务:

try {
    JSONObject json = $.parseJSON(result);
    if (json.has("Level")) {
        Object[] datas = $.makeArray(json.getJSONArray("Level"));
        for (Object data : datas) {
            JSONObject obj = (JSONObject) data;
            Object[] coordinates = $.makeArray(obj.getJSONArray("route"));
            for (Object coord : coordinates) {
                Map<String, ?> map = $.map((JSONObject) coord);
                double latitude = (Double) map.get("lat");
                double longitude = (Double) map.get("lgn");
                //TODO: do something with these values
            }
        }
    }
    else {
        Log.d("JSON", "Result does not contain 'Levels' variable");
    }
}
catch (Throwable t) {
    t.printStackTrace();
}
于 2013-07-29T02:13:43.453 回答