解析双嵌套 JSON - Volley
Parsing double nested JSON - Volley
我正在尝试从 url 解析 JSON 但 JSON 恰好是双重嵌套的,我不确定如何让它与我的一起工作代码
这是 JSON 及其 link:
{
"status":"success",
"data":{
"city":"London",
"state":"England",
"country":"United Kingdom",
"location":{
"type":"Point",
"coordinates":[
0.040725,
51.456357
]
},
"current":{
"weather":{
"ts":"2022-03-12T19:00:00.000Z",
"tp":9,
"pr":1008,
"hu":76,
"ws":5.14,
"wd":130,
"ic":"01n"
},
"pollution":{
"ts":"2022-03-12T19:00:00.000Z",
"aqius":27,
"mainus":"p2",
"aqicn":9,
"maincn":"p2"
}
}
}
}
代码:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONArray jsonArray = new JSONArray();
//Accessing "data" in the JSON
jsonArray.put(response.get("data"));
for (int i = 0; i < jsonArray.length(); i++){
JSONObject data = jsonArray.getJSONObject(i);
String cityName = data.getString("city");
String stateName = data.getString("state");
String countryName = data.getString("country");
}
//Notifying the adapter of the new changes
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}, Throwable::printStackTrace);
requestQ.add(request);
}
目标:
我希望函数读取“current”,然后读取“weather”,然后获取“tp”的值,就像我获取 cityName、stateName 等的值一样
我知道之前已经回答了这个问题,但我没有找到双嵌套 JSONs
非常感谢。
您可以通过
获取嵌套对象
yourObject.getJSONObject("weather")
在你的情况下,它将是:
data.getJSONObject("current").getJSONObject("weather").getInt("tp");
此外,您可以使用库 gson 将 json 字符串映射到 Java class.
我正在尝试从 url 解析 JSON 但 JSON 恰好是双重嵌套的,我不确定如何让它与我的一起工作代码 这是 JSON 及其 link:
{
"status":"success",
"data":{
"city":"London",
"state":"England",
"country":"United Kingdom",
"location":{
"type":"Point",
"coordinates":[
0.040725,
51.456357
]
},
"current":{
"weather":{
"ts":"2022-03-12T19:00:00.000Z",
"tp":9,
"pr":1008,
"hu":76,
"ws":5.14,
"wd":130,
"ic":"01n"
},
"pollution":{
"ts":"2022-03-12T19:00:00.000Z",
"aqius":27,
"mainus":"p2",
"aqicn":9,
"maincn":"p2"
}
}
}
}
代码:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONArray jsonArray = new JSONArray();
//Accessing "data" in the JSON
jsonArray.put(response.get("data"));
for (int i = 0; i < jsonArray.length(); i++){
JSONObject data = jsonArray.getJSONObject(i);
String cityName = data.getString("city");
String stateName = data.getString("state");
String countryName = data.getString("country");
}
//Notifying the adapter of the new changes
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}, Throwable::printStackTrace);
requestQ.add(request);
}
目标:
我希望函数读取“current”,然后读取“weather”,然后获取“tp”的值,就像我获取 cityName、stateName 等的值一样 我知道之前已经回答了这个问题,但我没有找到双嵌套 JSONs
非常感谢。
您可以通过
获取嵌套对象yourObject.getJSONObject("weather")
在你的情况下,它将是:
data.getJSONObject("current").getJSONObject("weather").getInt("tp");
此外,您可以使用库 gson 将 json 字符串映射到 Java class.