JSON 响应值如下所示 "types": [ "sublocality", "political"]
。如何获取类型的第一个值或如何获取单词sublocality?
最佳答案
String string = yourjson;
JSONObject o = new JSONObject(yourjson);
JSONArray a = o.getJSONArray("types");
for (int i = 0; i < a.length(); i++) {
Log.d("Type", a.getString(i));
}
如果您只解析上面提供的行,这将是正确的。请注意,要从 GoogleMaps 地理编码访问类型,您应该获得一组结果,而不是 address_components,然后您可以访问对象 components.getJSONObject(index)。
这是一个简单的实现,它只解析 formatted_address - 我在我的项目中需要的。
private void parseJson(List<Address> address, int maxResults, byte[] data)
{
try {
String json = new String(data, "UTF-8");
JSONObject o = new JSONObject(json);
String status = o.getString("status");
if (status.equals(STATUS_OK)) {
JSONArray a = o.getJSONArray("results");
for (int i = 0; i < maxResults && i < a.length(); i++) {
Address current = new Address(Locale.getDefault());
JSONObject item = a.getJSONObject(i);
current.setFeatureName(item.getString("formatted_address"));
JSONObject location = item.getJSONObject("geometry")
.getJSONObject("location");
current.setLatitude(location.getDouble("lat"));
current.setLongitude(location.getDouble("lng"));
address.add(current);
}
}
catch (Throwable e) {
e.printStackTrace();
}
}
关于android - 如何在android中获取json数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14708935/