从Java中的JSON响应获取字符串
无法理解如何获取JSON响应的字符串。从openweathermapapi()中,我们希望获得第一个temp_min和temp_max 我曾尝试在JSON格式化程序中发布JSON响应,并在逻辑上进行检查,但这对我没有多大帮助。在整个谷歌尝试了不同的解决方案 我这边的最后一次尝试是:从Java中的JSON响应获取字符串,java,json,Java,Json,无法理解如何获取JSON响应的字符串。从openweathermapapi()中,我们希望获得第一个temp_min和temp_max 我曾尝试在JSON格式化程序中发布JSON响应,并在逻辑上进行检查,但这对我没有多大帮助。在整个谷歌尝试了不同的解决方案 我这边的最后一次尝试是: JSONObject jsonObject = new JSONObject(response); JSONArray array = jsonObject.getJSONArray("list"); JSONObj
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("list");
JSONObject firstObject = (JSONObject)array.get(0);
String tempmax = firstObject.getJSONObject("main").getString("temp_max");
String tempmin = firstObject.getJSONObject("main").getString("temp_min");
从以下API响应中,我希望接收temp_min和temp_max:
{
"cod":"200",
"message":0.0032,
"cnt":36,
"list":[
{
"dt":1487246400,
"main":{
"temp":286.67,
"temp_min":281.556,
"temp_max":286.67,
"pressure":972.73,
"sea_level":1046.46,
"grnd_level":972.73,
"humidity":75,
"temp_kf":5.11
},
"weather":[ ],
"clouds":{ },
"wind":{ },
"sys":{ },
"dt_txt":"2017-02-16 12:00:00"
},
[..]
我希望从API响应中获得temp_min和temp_max值,但目前它只是空的。我刚刚使用最新版本的库检查了您的代码。我从本地文件加载了json内容,我必须改变读取温度值的方式:
public static void main(String[] args) throws IOException {
String collect = Files.lines(Paths.get("src/main/resources/waether.json")).collect(Collectors.joining());
JSONObject jsonObject = new JSONObject(collect);
JSONArray array = jsonObject.getJSONArray("list");
JSONObject firstObject = (JSONObject)array.get(0);
double tempmax = firstObject.getJSONObject("main").getDouble("temp_max");
double tempmin = firstObject.getJSONObject("main").getDouble("temp_min");
System.out.println("Temp min " + tempmin);
System.out.println("Temp max " + tempmax);
}
输出为:
Temp min 259.086
Temp max 261.45
正如您所见,我必须使用
getDouble
方法,因为这些值不是json字符串,而是数字。我不确定您使用的是这个库的哪个版本,但它的最新版本可以工作。非常感谢michalk和其他人的帮助。对michalk的答案进行了一些编辑,因此它符合我的项目,解决了我遇到的问题。我没有收到错误,只是变量tempmax和tempmin为空(空白),但我希望这两个值都从API请求中读取。在这种情况下,它应该类似于:tempmax=286.67 tempmin=281.556您可能存在强制转换问题。尝试将此行强制转换为String(String)firstObject.getJSONObject(“main”).getString(“temp_max”)代码>我还建议将try-catch添加到代码中,就好像您没有捕获到错误一样