user3872094 user3872094 - 29 days ago 7
Java Question

getting nested maps in Java

I've the below json code.

{
"main": {
"temp": 301.335,
"pressure": 951.08,
"humidity": 45,
"temp_min": 301.335,
"temp_max": 301.335,
"sea_level": 1025.43,
"grnd_level": 951.08
}
}


And I'm using the below java code to get this data.

This above json is stored in a String
text
.

System.out.println(text);

ObjectMapper mapper = new ObjectMapper();

// read JSON from a file
Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
});

System.out.println(map.get("main"));

Map<String, Object> mapIn = mapper.readValue(map.get("main").toString(),
new TypeReference<Map<String, Object>>() {
});

System.out.println(mapIn);


Here i want to print the
temp
value in my console. But as of now I get the below o/p with exception.

{
"coord": {
"lon": 106.85,
"lat": -6.21
},
"weather": [{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03d"
}],
"base": "stations",
"main": {
"temp": 304.15,
"pressure": 1007,
"humidity": 62,
"temp_min": 304.15,
"temp_max": 304.15
},
"visibility": 8000,
"wind": {
"speed": 3.1,
"deg": 320
},
"clouds": {
"all": 40
},
"dt": 1478244600,
"sys": {
"type": 1,
"id": 8043,
"message": 0.0084,
"country": "ID",
"sunrise": 1478211943,
"sunset": 1478256397
},
"id": 1642911,
"name": "Jakarta",
"cod": 200
} {
temp = 304.15, pressure = 1007, humidity = 62, temp_min = 304.15, temp_max = 304.15
}
Exception in thread "main"
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.lang.String
at Jackson2Example.main(Jackson2Example.java: 51)


please let me know where am I going wrong, how can I fix this and get
temp
value.

Thanks

Answer

You need not to call mapper.readValue again. try this:

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


Map<String, Object> mainMap = (Map<String, Object>) map.get("main");        

System.out.println(mainMap.get("temp"));
Comments