user3872094 user3872094 - 17 days ago 5
Java Question

retrieve a value from json array using jackson

I'm writing a code where I need to get the value from a json Array. and my jdon result 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 which I'm using to get this weather 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 result string.

Thanks

Answer

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);