gpt4 book ai didi

java - Android - 如何解析 JSONObject 和 JSONArrays

转载 作者:行者123 更新时间:2023-11-28 12:47:13 25 4
gpt4 key购买 nike

我的版本是 Android 2.2 Google API 8 ,我从模拟器运行。我正在尝试尝试访问此 JSON 对象中的位置。我使用后得到这个

 InputStream instream = entity.getContent();

JSONObject myAwway = new JSONObject(convertStreamToString(instream));

Google 文档说它返回一个数组,但带有大括号,它看起来像一个对象。

我需要访问位置字段中的纬度和经度并存储为 double 值。

我进行了搜索,但似乎只找到了有关简单文件的帮助。

{
"results" : [
{
"address_components" : [
{
"long_name" : "20059",
"short_name" : "20059",
"types" : [ "postal_code" ]
},
{
"long_name" : "Washington D.C.",
"short_name" : "Washington D.C.",
"types" : [ "locality", "political" ]
},
{
"long_name" : "District of Columbia",
"short_name" : "DC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Washington D.C., DC 20059, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 38.924920,
"lng" : -77.0178720
},
"southwest" : {
"lat" : 38.9189910,
"lng" : -77.02261200000001
}
},
"location" : {
"lat" : 38.92177780,
"lng" : -77.01974260
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 38.92510312068017,
"lng" : -77.01709437931984
},
"southwest" : {
"lat" : 38.91880787931983,
"lng" : -77.02338962068018
}
}
},
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}

最佳答案

JSONObject jObject = new JSONObject(convertStreamToString(instream));
JSONArray results = jObject.getJSONArray("result");
JSONObject geometry = results.getJSONObject(2);
JSONObject bounds = geometry.getJSONObject("bounds");
JSONObject northeast = geometry.getJSONObject("northeast");

double nLat = Double.parseDouble(northeast.getString("lat").toString());
double nLng = Double.parseDouble(northeast.getString("lng").toString());

这应该为您提供东北地区的纬度/经度双倍。东南是一样的,只是将东北替换为东南。

关于java - Android - 如何解析 JSONObject 和 JSONArrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com