json字段映射到bean

504 阅读1分钟
json字段映射到bean:
    @seehttps://blog.csdn.net/weixin_34366546/article/details/91387447

json:
    {"location":"广州","temp":15,"weather":"多云"}
    {"place":"深圳","temperature":35,"outlook":"晴天"}

使用Jackson:        
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependenc>

    示例:
        bean代码:
            @JsonProperty("location")
            @JsonAlias({"place", "******"})
            private String location;

            @JsonProperty("temp")
            @JsonAlias({"temperature", "******"})
            private int temp;

            @JsonProperty("outlook")
            @JsonAlias({"weather", "******"})
            private String outlook;

        test:
            ObjectMapper mapper = new ObjectMapper();
            Weather weather = mapper.readValue("{"location": "广州","temp": 15,"weather": "多云"}", Weather.class);

使用Gson:
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
        <scope>test</scope>
    </dependency>

    示例:
        bean代码:
            @SerializedName(value="location", alternate={"place"})
            private String location;

            @SerializedName(value="temp", alternate={"temperature"})
            private int temp;

            @SerializedName(value="outlook", alternate={"weather"})
            private String outlook;

        test:
            Gson gson = new GsonBuilder().create();
            Weather weather = gson.fromJson("{"location": "广州","temp": 15,"weather": "多云"}", Weather.class);