-2

From this json code

{
    "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"
            }
        ]
    }

how do i get list.main.temp and list.weather.main which is in weather array?

My code to get list.main.tempis the following but it doesn't work:

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

Can anyone help me to fix the code and help me to get list.weather.main?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Daniele
  • 65
  • 2
  • 12

2 Answers2

0

I think this will help.

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

where MyObject is the object you want to deserialize to. Then you can just call into the properties as you would normally in Java.

Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • 1
    That's a lot of unnecessary overhead just to parse out a field – OneCricketeer Jan 13 '18 at 18:05
  • Well you wouldn't necessarily just be parsing out a field. Maybe in this particular instance that's all you want to do, but a lot of the time you want the entire object – Woody1193 Jan 13 '18 at 18:32
0

You cannot hop into the the middle of a JSON object.

The city element contains the list

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

You also need a loop around

array.getJSONObject(i)

You might want to look at Json-path to query data easier

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245