java - 如何反序列化与我的 Java 类同名的嵌套 JSON 对象

标签 java spring-boot jackson

我正在尝试映射此 JSON

{
"coord": {
    "lon": 26.94,
    "lat": 43.27
},
"weather": [
    {
        "id": 802,
        "main": "Clouds",
        "description": "scattered clouds",
        "icon": "03d"
    }
],
"base": "model",
"main": {
    "temp": 19.3,
    "pressure": 1012,
    "humidity": 66,
    "temp_min": 19.3,
    "temp_max": 19.3,
    "sea_level": 1012,
    "grnd_level": 971
},
"wind": {
    "speed": 6.91,
    "deg": 182
},
"clouds": {
    "all": 38
},
"dt": 1573204594,
"sys": {
    "country": "BG",
    "sunrise": 1573188939,
    "sunset": 1573224978
},
"timezone": 7200,
"id": 727233,
"name": "Shumen",
"cod": 200
}

到我自己创建的java对象

    package com.kosev.willitrain.model;
    import com.fasterxml.jackson.annotation.JsonAlias;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import java.util.Map;

    public class Weather {
        @JsonProperty("name")
        private String cityName;
        private String type; // for weather type eg: Cloudy, Sunny, Raining etc...
        private float temp;
        private float tempMin;
        private float tempMax;
        private float windSpeed;
        private String icon;
        private float lon;
        private float lat;

        public Weather(){}

        @JsonProperty("main")
        private void unpackMain(Map<String,String> main) {
            temp = Float.parseFloat(main.get("temp"));
            tempMin = Float.parseFloat(main.get("temp_min"));
            tempMax = Float.parseFloat(main.get("temp_max"));
        }

        @JsonProperty("coord")
        private void unpackCoord(Map<String,String> coord) {
            lon = Float.parseFloat(coord.get("lon"));
            lat = Float.parseFloat(coord.get("lat"));
        }

        @JsonProperty("weather")
        private void unpackWeather(Map<String,String> weather) {
            type = weather.get("main");
            icon = weather.get("icon");
        }
    }

我得到的错误是这样的:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.LinkedHashMap<java.lang.Object,java.lang.Object> out of START_ARRAY token at [Source: (PushbackInputStream); line: 1, column: 46] (through reference chain: com.kosev.willitrain.model.Weather["weather"])

最佳答案

    package com.sample.demo;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DemoApplicationTests {

    public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String response = "{\n" + "\"coord\": {\n" + "    \"lon\": 26.94,\n" + "    \"lat\": 43.27\n" + "},\n"
                + "\"weather\": [\n" + "    {\n" + "        \"id\": 802,\n" + "        \"main\": \"Clouds\",\n"
                + "        \"description\": \"scattered clouds\",\n" + "        \"icon\": \"03d\"\n" + "    }\n"
                + "],\n" + "\"base\": \"model\",\n" + "\"main\": {\n" + "    \"temp\": 19.3,\n"
                + "    \"pressure\": 1012,\n" + "    \"humidity\": 66,\n" + "    \"temp_min\": 19.3,\n"
                + "    \"temp_max\": 19.3,\n" + "    \"sea_level\": 1012,\n" + "    \"grnd_level\": 971\n" + "},\n"
                + "\"wind\": {\n" + "    \"speed\": 6.91,\n" + "    \"deg\": 182\n" + "},\n" + "\"clouds\": {\n"
                + "    \"all\": 38\n" + "},\n" + "\"dt\": 1573204594,\n" + "\"sys\": {\n" + "    \"country\": \"BG\",\n"
                + "    \"sunrise\": 1573188939,\n" + "    \"sunset\": 1573224978\n" + "},\n" + "\"timezone\": 7200,\n"
                + "\"id\": 727233,\n" + "\"name\": \"Shumen\",\n" + "\"cod\": 200\n" + "}";
        Weather weather = objectMapper.readValue(response, Weather.class);
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Weather {
    @JsonProperty("name")
    private String cityName;
    private String type; // for weather type eg: Cloudy, Sunny, Raining etc...
    private float temp;
    private float tempMin;
    private float tempMax;
    private float windSpeed;
    private String icon;
    private float lon;
    private float lat;

    @JsonIgnoreProperties("base")
    public Weather() {
    }

    @JsonProperty("main")
    private void unpackMain(Map<String, String> main) {
        temp = Float.parseFloat(main.get("temp"));
        tempMin = Float.parseFloat(main.get("temp_min"));
        tempMax = Float.parseFloat(main.get("temp_max"));
    }

    @JsonProperty("coord")
    private void unpackCoord(Map<String, String> coord) {
        lon = Float.parseFloat(coord.get("lon"));
        lat = Float.parseFloat(coord.get("lat"));
    }

    @JsonProperty("weather")
    private void unpackWeather(List<Map<String, String>> weather) {
        System.out.println(weather);
        type = weather.get(0).get("main"); // Taken first element , change as per your requirement
        icon = weather.get(0).get("icon");
    }
}

天气应该是 map 列表,而不是 map 。

关于java - 如何反序列化与我的 Java 类同名的嵌套 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58764685/

相关文章:

spring-boot - Spring Boot 项目中的 Liquibase 模块和变量

java - @RequestParam Map<String, String> 在 Spring Boot 中打印变量名称作为键

spring - 处理 POM : [FATAL] Non-parseable POM. ..PITarget 时出现 Maven 错误,保留 xml 名称

java - HttpMediaTypeNotAcceptableException : Could not find acceptable representation spring mvc 4. 1.5 与 com.fasterxml 2.5.1

java - request.getHeader ("authorization") 从 Tomcat header 中丢失

java - 使用java使用ssl SOAP

java - 恢复 hibernate 连接

java - 使用java程序更新mysql数据库

json - Jersey Jackson 数据实体在收集时过滤 JsonMappingException

java - 实体参数的多态 JSON 反序列化 (Jackson) (Google Cloud Endpoints)