0

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

2
  • why are you calling mapper.readValue again. This time you are calling it with String (not Json String). Commented Nov 4, 2016 at 8:50
  • @SachinGupta, this is where I'm stuck... unable to know how to get that temp from output Commented Nov 4, 2016 at 8:53

1 Answer 1

1

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

Haa, now I got this, this would in turn get value from the nested json. Thank you verymuch...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.