从json获取值时出现问题?

时间:2018-04-03 13:57:47

标签: android

这是我的json回复,

    "stops": [
      {
        "location": "The Sachdevs, 17, GAA 4th Ln, Thousand Lights West, Nungambakkam, Chennai, Tamil Na
        "latlong": {
            "lon": 80.250285901129,
            "lat": 13.05583158449
        },
        "stop_code": "stop_1522754972",
        "status": ""
    },
]
此行

错误:

  

jSONObject cat_object2 = latLong_object.getJSONObject(j);宾语   不能在int中适用

这是我的java代码, 任何人都给我解决方案。

              Object stops = response_object.get("stops");
                        if (stops instanceof JSONArray) {

                            JSONArray stops_array = response_object.getJSONArray("stops");
                            if (stops_array.length() > 0) {
                                maplist.clear();

                                for (int k = 0; k < stops_array.length(); k++) {

                                    JSONObject cat_object = stops_array.getJSONObject(k);

                                    MultipleLatLongPojo pojo = new MultipleLatLongPojo();
                                    pojo.setLocation(cat_object.getString("location"));
                                    pojo.setStopcode(cat_object.getString("stop_code"));
                                    pojo.setStatus(cat_object.getString("status"));

                                    JSONObject latLong_object = cat_object.getJSONObject("latlong");
                                    if (latLong_object.length() > 0) {
                                        for (int j = 0; j < latLong_object.length(); j++) {
                                            JSONObject cat_object2 = latLong_object.getJSONObject(j);
                                            MultipleLatLongPojo pojo2 = new MultipleLatLongPojo();
                                            pojo2.setMulti_lat(cat_object2.getString("lon"));
                                            pojo2.setMulti_lon(cat_object2.getString("lat"));

                                        }
                                    } else {

                                    }

                                }
                            }
                        }

1 个答案:

答案 0 :(得分:0)

json中的latlong属性不是数组,而是具有两个属性(latlon)的对象,因此您不需要遍历它的长度和此部分你的代码:

JSONObject latLong_object = cat_object.getJSONObject("latlong");
if (latLong_object.length() > 0) {
   for (int j = 0; j < latLong_object.length(); j++) {
      JSONObject cat_object2 = latLong_object.getJSONObject(j);
      MultipleLatLongPojo pojo2 = new MultipleLatLongPojo();
      pojo2.setMulti_lat(cat_object2.getString("lon"));
      pojo2.setMulti_lon(cat_object2.getString("lat"));
   }
}

应该是这样的:

JSONObject latLong_object = cat_object.getJSONObject("latlong");
if(latLong_object != null) {
    MultipleLatLongPojo pojo2 = new MultipleLatLongPojo();
    pojo2.setMulti_lat(latLong_object.getString("lon"));
    pojo2.setMulti_lon(latLong_object.getString("lat"));
}