android - 如何从android中的JSON中的嵌套数组中获取数据?
问题描述
protected Void doInBackground(Void...arg0) { HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray array = jsonObj.getJSONArray("list");
for (int i = 0; i < array.length(); i++) {
JSONObject child = array.getJSONObject(i);
String name = child.getString("name");
JSONObject coord = child.getJSONObject("coord");
String lat = coord.getString("lat");
String lon = coord.getString("lon");
JSONObject main = child.getJSONObject("main");
String temp = main.getString("temp");
JSONObject clouds = child.getJSONObject("clouds");
String cl = clouds.getString("all");
JSONObject des = child.getJSONObject("weather");
String de = des.getString("description");
HashMap<String, String> weather = new HashMap<>();
weather.put("name", name);
weather.put("temp", temp);
weather.put("cl", cl);
weather.put("lat", lat);
weather.put("lon", lon);
weather.put("des", de);
WeatherList.add(weather);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(() -> Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show());
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(() -> Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show());
}
return null;
}
这是我的 JSON 数据我如何从天气数组中获取“描述”数据?
{
"list": [
{
"id": 1270077,
"name": "Hinganghāt",
"coord": {
"lat": 20.5667,
"lon": 78.8333
},
"main": {
"temp": 304.82,
"feels_like": 308.91,
"temp_min": 304.82,
"temp_max": 304.82,
"pressure": 1000,
"humidity": 58,
"sea_level": 1000,
"grnd_level": 977
},
"dt": 1626242961,
"wind": {
"speed": 3.75,
"deg": 91
},
"sys": {
"country": "IN"
},
"rain": null,
"snow": null,
"clouds": {
"all": 65
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
]
},
{
"id": 1256206,
"name": "Sindi",
"coord": {
"lat": 20.8,
"lon": 78.8667
},
"main": {
"temp": 304.64,
"feels_like": 308.26,
"temp_min": 304.64,
"temp_max": 304.64,
"pressure": 1000,
"humidity": 57,
"sea_level": 1000,
"grnd_level": 974
},
"dt": 1626242995,
"wind": {
"speed": 4.02,
"deg": 92
},
"sys": {
"country": "IN"
},
"rain": null,
"snow": null,
"clouds": {
"all": 54
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
]
}
]
}
解决方案
推荐阅读
- c - 用户输入一个数字,程序应该用字符包围它
- python - 使用包含年份的数据框索引作为 x 轴
- aws-lambda - 如何使用 AWS Lambda 和 MSK (Kafka) 事件流应用背压
- php - 类 Illuminate\Database\Eloquent\Builder 的对象无法转换为 int
- javascript - 我无法从 javascript 发布 json 对象
- c++ - 是否有适当的方法来根据编译时传递的模板值参数来别名类型(c ++)
- mysql - 仅当 endDate 不大于今天时如何获得结果
- javascript - 是否可以在对象模式中包含不同的键?
- python - 删除重复项而不更改二维列表中的顺序
- kdb - KDB/Q 我们如何计算移动中位数