我正在使用Google的地理编码API来获取包含地理位置位置信息的JSON字符串。这是我从谷歌回来的字符串。
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "550 Susong Dr, Morristown, TN 37814, USA",
"address_components": [ {
"long_name": "550",
"short_name": "550",
"types": [ "street_number" ]
}, {
"long_name": "Susong Dr",
"short_name": "Susong Dr",
"types": [ "route" ]
}, {
"long_name": "Morristown",
"short_name": "Morristown",
"types": [ "locality", "political" ]
}, {
"long_name": "Morristown",
"short_name": "Morristown",
"types": [ "administrative_area_level_3", "political" ]
}, {
"long_name": "Hamblen",
"short_name": "Hamblen",
"types": [ "administrative_area_level_2", "political" ]
}, {
"long_name": "Tennessee",
"short_name": "TN",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United States",
"short_name": "US",
"types": [ "country", "political" ]
}, {
"long_name": "37814",
"short_name": "37814",
"types": [ "postal_code" ]
} ],
"geometry": {
"location": {
"lat": 36.2422740,
"lng": -83.3219410
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 36.2391264,
"lng": -83.3250886
},
"northeast": {
"lat": 36.2454216,
"lng": -83.3187934
}
}
}
}] }
但是,当我在Java中运行以下代码时,我得到一个“java.lang.ClassCastException:java.lang.String与net.sf.json.JSONObject不兼容”错误。
URL url = new URL(URL + "&address=" + URLEncoder.encode(address, "UTF-8") + "&signature=" + key);
URLConnection conn = url.openConnection();
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
IOUtils.copy(conn.getInputStream(), output);
output.close();
GAddress gaddr = new GAddress();
JSONObject json = JSONObject.fromObject(output.toString());
JSONObject placemark = (JSONObject) query(json, "Placemark[0]");
我不知道为什么我会收到错误。 Google响应对我来说看起来像是一个有效的JSON字符串。其他人有这个问题吗?我愿意使用net.sf.json以外的东西,如果由于某种原因它与谷歌玩得不好。
谢谢,
安德鲁
答案 0 :(得分:1)
看起来您正在从原始函数调用中获取字符串。当然,你可以添加
System.out.println(query(json,“Placemark [0]”)。class);
就在最后一行之前。这将为您提供您正在处理的对象的类型。