在Google地理编码中使用net.sf.json.JSONObject时获取java.lang.ClassCastException
我正在使用Google的地理编码API获取包含地理编码位置信息的JSON字符串。这是我从谷歌得到的字符串在Google地理编码中使用net.sf.json.JSONObject时获取java.lang.ClassCastException,java,json,google-geocoder,Java,Json,Google Geocoder,我正在使用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":
{
"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不兼容”错误
我不知道为什么会出错。谷歌的响应在我看来像是一个有效的JSON字符串。还有其他人对此有问题吗?如果出于某种原因,net.sf.json与谷歌的关系不好,我愿意使用net.sf.json以外的东西
谢谢
Andrew看起来您从原始函数调用中得到了一个字符串。当然,您可以添加 System.out.println(查询(json,“Placemark[0]”)类)
就在最后一行之前。这将为您提供您正在处理的对象的类型。在最后一行之前输入“System.out.println(query(json),“Placemark[0]”表示返回java.lang.String。)时是否返回
字符串
。从query()
返回JSONObject或删除强制转换和赋值。请参阅下面的注释。感谢Nishant。它说这是一个java.lang.String。显然,我所看到的代码使用的是来自Google的旧版本的响应,它得到了意想不到的结果。我从谷歌那里得到了回复,并且能够找出哪里发生了类型不匹配。谢谢,伙计们。
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]");