在Java中获取嵌套映射

时间:2016-11-04 08:14:07

标签: java json

我有以下json代码。

{
"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
  }
}

我正在使用下面的java代码来获取这些数据。

以上json存储在字符串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);

这里我想在控制台中打印temp值。但截至目前,我得到了以下的o / p,例外。

{
  "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)

请让我知道我哪里出错了,我该如何解决此问题并获得temp价值。

由于

1 个答案:

答案 0 :(得分:1)

您无需再次致电aggregate()。试试这个:

mapper.readValue