这是我从 OpenWeatherMap 收到的 JSON 响应:
{
"coord": {
"lon": 85.84,
"lat": 20.26
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.15,
"pressure": 1007,
"humidity": 70,
"temp_min": 305.15,
"temp_max": 305.15
},
"visibility": 5000,
"wind": {
"speed": 4.1,
"deg": 170
},
"clouds": {
"all": 20
},
"dt": 1551686400,
"sys": {
"type": 1,
"id": 9113,
"message": 0.0037,
"country": "IN",
"sunrise": 1551659668,
"sunset": 1551702153
},
"id": 1275817,
"name": "Bhubaneswar",
"cod": 200
}
虽然我可以通过使用下面的代码来使用 Weather,但无法将 main 转换为数组。无论如何我可以将粗体响应转换为数组或字符串。
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for(int i=0;i<arr.length();i++)
{
JSONObject jsonPart = arr.getJSONObject(i);
String main = jsonPart.getString("main");
String description =jsonPart.getString("description");
if(main !="" && description !="")
{
message += main + " : " + description + "\r\n";
}
}
最佳答案
建议是,不要手动解析 JSON。使用第三方库,如 Gson解析 JSON。这样您就不会遇到任何拼写错误,并让库为您处理解析。
关于java - 如何将 JSON 响应转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979897/