如何从 json 获取参数

How do I get parameters from json

来自这个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.temp 的代码如下,但它不起作用:

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

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

我认为 this 会有所帮助。

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

其中 MyObject 是您要反序列化的对象。然后您可以像通常在 Java.

中那样调用属性

你不能跳到 JSON 物体的中间。

city 元素包含列表

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

你还需要一个循环

array.getJSONObject(i)

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