从JSON取值时遇类型转换错误,求Java解决方案
解决从JSON中获取嵌套对象时的类型错误问题
首先,先修正你提供的JSON语法问题(原JSON存在字符串未闭合、数组尾元素多余逗号的错误),正确的结构如下:
"stops": [ { "location": "The Sachdevs, 17, GAA 4th Ln, Thousand Lights West, Nungambakkam, Chennai, Tamil Nadu", "latlong": { "lon": 80.250285901129, "lat": 13.05583158449 }, "stop_code": "stop_1522754972", "status": "" } ]
你遇到的错误Object cannot be applied to int,根源是错误地将latlong这个JSONObject当作JSONArray处理。从JSON结构能看到,每个stop条目里的latlong是单个对象(用{}包裹),不是数组([]),所以它没有数组索引,不能用整数j去调用getJSONObject()——这个方法对JSONObject来说,参数需要是字符串类型的键名(比如"lon"),而非整数索引。
下面是修正后的Java代码示例,用于正确遍历stops数组并提取经纬度:
// 假设response_object是已解析完成的根JSONObject Object stops = response_object.get("stops"); if (stops instanceof JSONArray) { JSONArray stopsArray = (JSONArray) stops; // 遍历每个stop对象 for (int i = 0; i < stopsArray.length(); i++) { JSONObject stopObj = stopsArray.getJSONObject(i); // 获取嵌套的latlong对象 JSONObject latLongObj = stopObj.getJSONObject("latlong"); // 提取经纬度值 double lon = latLongObj.getDouble("lon"); double lat = latLongObj.getDouble("lat"); // 这里可以添加你的业务逻辑,比如打印或存储坐标 System.out.printf("Stop %d: 经度=%.6f, 纬度=%.6f%n", i+1, lon, lat); } }
核心要点:
- 先明确JSON中各字段的类型:
stops是数组,latlong是单个对象 - 遍历数组时用索引操作数组元素,获取嵌套对象时用键名字符串调用
getJSONObject()
内容的提问来源于stack exchange,提问作者anafroz
相关产品推荐
相关产品推荐

