我正在嘗試從 url 決議 JSON,但 JSON 恰好是雙重嵌套的,我不知道如何使它與我的代碼一起使用這是 JSON 及其鏈接:
{
"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);
}
目標:
我希望函式先讀取“當前”,然后讀取“天氣”,然后獲取“tp”的值,就像我獲取 cityName、stateName 等的值一樣我知道這個問題之前已經回答過,但我沒有找到雙嵌套 JSON 的東西
提前非常感謝。
uj5u.com熱心網友回復:
您可以通過以下方式獲取嵌套物件
yourObject.getJSONObject("天氣")
在您的情況下,它將是:
data.getJSONObject("current").getJSONObject("weather").getInt("tp");
此外,您可以使用庫gson將 json 字串映射到 Java 類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442684.html
上一篇:將json物件分離到不同的索引中