gpt4 book ai didi

Java JSONObject.getJSONArray 始终返回 null

转载 作者:行者123 更新时间:2023-12-01 19:02:29 25 4
gpt4 key购买 nike

我想使用 Google 距离矩阵 API 来获取两个位置之间行驶所需的持续时间。但是当我尝试从返回的数据(JSON 编码)获取持续时间时,方法 getJSONArray 始终返回 null。

以下是 Google 发送的数据:

{
"destination_addresses" : [ "Rome, Metropolitan City of Rome, Italy" ],
"origin_addresses" : [ "Berlin, Germany" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,501 km",
"value" : 1501458
},
"duration" : {
"text" : "15 hours 5 mins",
"value" : 54291
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}

这是获取持续时间的方法:

public static int getDurationFromJSON(String json){
try {
JSONObject jsonObj = new JSONObject(json)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray ("elements")
.getJSONObject(0)
.getJSONObject("duration");

return (int)(jsonObj.getInt("value") / 60.0f + 0.5f);
} catch (Exception e) {
e.printStackTrace();
}

return -1;
}

getJSONArray("rows") 返回 null。

最佳答案

我不确定为什么你会得到 null,但这一行似乎过多:

(int)(Integer.parseInt(String.valueOf(jsonObj.getInt("value"))) / 60.0f + 0.5f);

JsonObj.getInt("Value) 将返回一个 int,为什么要将其转换为字符串,然后将其解析回 Int,然后再次将其转换回 INT?

这可以简化为这样

 return(int)((jsonObj.getInt("value")/60.0f) +0.5f)

对于 null,我会使用调试器并检查传入的 JSON,并确保它是您认为的那样。

此外,正如其他人所建议的那样,使用 RestTemplate 之类的东西将 json 自动解析为 native 映射对象将使您的生活更轻松。

关于Java JSONObject.getJSONArray 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59614175/

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