我正在尝试从以下json
中获取位置名称http://maps.googleapis.com/maps/api/geocode/json?latlng=18.486096,73.802027&sensor=false回复JSON的特定地址。我正在开发一个Android应用程序来使用api反转地理编码。
这是下面的代码..
public class MyGeocoder
{
public static String getUserLocation(Location loc) {
String userlocation = null;
String readUserFeed = readUserLocationFeed((Double.toString(loc.getLatitude())) +
","+( Double.toString(loc.getLongitude())));
try {
//JSONObject Strjson = new JSONObject(readUserFeed);
JSONArray jsonArray = new JSONArray(readUserFeed);
JSONObject jsonObject=jsonArray.getJSONObject(0);
userlocation = jsonObject.getString("locality").toString();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("User Location ", userlocation);
return userlocation;
}
public static String readUserLocationFeed(String address) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?
latlng="+ address + "&sensor=false");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
//Log.e(ReverseGeocode.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
答案 0 :(得分:0)
对于解析json,你做错了。首先,网址会返回JSONObject
,其中包含JSONArray
“结果”和字段“状态”。
所以你应该取消注释以下一行:
JSONObject Strjson = new JSONObject(readUserFeed);
我建议你查看状态字段的值,看看它没问题,它有这样的数据:
if(Strjson.getString("status").equals("OK")) { ... }
然后使用
获取JSONArray
JSONArray result = Strjson.getJSONArray("result");
并遍历每个JSONObject
以获取所需的字段值,但是你得到的东西是json不包含名称为“locality”的字段但包含为类型字段的值之一。