我如何从json获取参数

时间:2018-01-13 17:51:27

标签: java json openweathermap

从这个json代码

{
    "city": {
        "id": 1851632,
        "name": "Shuzenji",
        "coord": {
            "lon": 138.933334,
            "lat": 34.966671
        },
        "country": "JP",
        "cod": "200",
        "message": 0.0045,
        "cnt": 38,
        "list": [{
                "dt": 1406106000,
                "main": {
                    "temp": 298.77,
                    "temp_min": 298.77,
                    "temp_max": 298.774,
                    "pressure": 1005.93,
                    "sea_level": 1018.18,
                    "grnd_level": 1005.93,
                    "humidity": 87,
                    "temp_kf": 0.26
                },
                "weather": [{
                        "id": 804,
                        "main": "Clouds",
                        "description": "overcast clouds",
                        "icon": "04d"
                    }
                ],
                "clouds": {
                    "all": 88
                },
                "wind": {
                    "speed": 5.71,
                    "deg": 229.501
                },
                "sys": {
                    "pod": "d"
                },
                "dt_txt": "2014-07-23 09:00:00"
            }
        ]
    }

我如何获得天气数组中的list.main.temp和list.weather.main?

我的代码获取list.main.tempis以下但它不起作用:

JSONArray array = obj.getJSONArray("list");
 String temp = String.valueOf((Double) array.getJSONObject(i).getJSONObject("main").get("temp"));

任何人都可以帮我修复代码并帮我获取list.weather.main吗?

2 个答案:

答案 0 :(得分:0)

我认为this会有所帮助。

MyObject result = new ObjectMapper().readValue(json, MyObject.class);

其中MyObject是要反序列化的对象。然后,您可以像在Java中一样调用属性。

答案 1 :(得分:0)

您无法跳到JSON对象的中间。

city元素包含列表

obj.getJSONObject("city").getJSONArray("list");

你还需要一个循环

array.getJSONObject(i)

您可能希望查看Json-path以便更轻松地查询数据

相关问题