Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve a value from json array using jackson

Tags:

java

json

jackson

I'm writing a code where I need to get a specific value from a json array. My json is as below:

{
  "coord": {
    "lon": 68.37,
    "lat": 25.39
  },
  "weather": [{
    "id": 800,
    "main": "Clear",
    "description": "clear sky",
    "icon": "01d"
  }],
  "base": "stations",
  "main": {
    "temp": 302.645,
    "pressure": 1023.33,
    "humidity": 48,
    "temp_min": 302.645,
    "temp_max": 302.645,
    "sea_level": 1025.53,
    "grnd_level": 1023.33
  },
  "wind": {
    "speed": 1.81,
    "deg": 54.0002
  },
  "clouds": {
    "all": 0
  },
  "dt": 1479887201,
  "sys": {
    "message": 0.0023,
    "country": "PK",
    "sunrise": 1479865789,
    "sunset": 1479904567
  },
  "id": 1176734,
  "name": "Hyderabad",
  "cod": 200
}

I want to get the id from weather array. If there are many, I want to get the first item's id.

Please let me know how can I do this.

The code I'm using to get the weather array is:

text = builder.toString();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
});

List mainMap2 = (List) map.get("weather");
for (Object item : mainMap2) {
    System.out.println("itemResult" + item.toString());
}

Here, text is the json string.

like image 882
user3872094 Avatar asked May 12 '26 22:05

user3872094


1 Answers

Following line should do the trick

int id = (int)((Map)mainMap2.get(0)).get("id");

Modification of your code may be as follows:

text = builder.toString();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
});

List mainMap2 = (List) map.get("weather");
//for (Object item : mainMap2) {
//    System.out.println("itemResult" + item.toString());
//}
int id = (int)((Map)mainMap2.get(0)).get("id");
System.out.println(id);
like image 107
sazzad Avatar answered May 15 '26 12:05

sazzad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!