我正在使用 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 字符串。其他人有这个问题吗?如果出于某种原因它与 Google 不兼容,我愿意使用 net.sf.json 之外的其他东西。
谢谢,
安德鲁