user3872094
user3872094

Reputation: 3351

Retrieve a value from json array using 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.

Upvotes: 3

Views: 10858

Answers (2)

sazzad
sazzad

Reputation: 6267

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

Upvotes: 3

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

In jackson, JSON objects are converted into LinkedHashMap<String, Object>, so you simply need to cast your Object item into a Map<String, Object>, then get the value corresponding to the key id.

Something like this:

Integer id = null;
for (Object item : mainMap2) {
    Map<String, Object> mapItem = (Map<String, Object>) item;
    id = (Integer) mapItem.get("id");
    if (id != null) {
        // We have found an Id so we print it and exit from the for loop
        System.out.printf("Id=%d%n", id);
        break;
    }
}

Output:

Id=800

Upvotes: 2

Related Questions