杰克逊注释@JsonUnwrapped忽略@JsonProperty值

时间:2018-09-10 09:00:56

标签: jackson objectmapper jackson-databind

这是一个非常简单的场景,在该场景中,我获得了要解包进行序列化的值对象。不能使用自定义序列化器。

public class UnwrappedWithPropertyName {

    public static void main(String[] args) throws JsonProcessingException {

        final Address address = new Address(new Postcode("45678"));

        final ObjectMapper mapper = new ObjectMapper();

        System.out.println(mapper.writeValueAsString(address));
    }


    static class Address {

        @JsonUnwrapped
        @JsonProperty("postcode")
        private final Postcode postcode;

        Address(Postcode postcode) {
            this.postcode = postcode;
        }

        public Postcode getPostcode() {
            return postcode;
        }
    }

    static class Postcode {

        private final String value;

        Postcode(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }
}

这将导致

{"value":"45678"}
,而我期望的是
{"postcode":"45678"}

2 个答案:

答案 0 :(得分:1)

通过使用@JsonValue注释字段,可以从封闭的类中控制此类字段的名称。

idle.clearInterrupts()

答案 1 :(得分:0)

@JsonProperty("postcode")移至private final String value;