読者です 読者をやめる 読者になる 読者になる

decadence

個人のメモ帳

Jackson Annotation

jackson

See Jackson Annotations · FasterXML/jackson-annotations Wiki · GitHub

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        // too many feature for serialization and deserialization
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true);

        // ======>> Person1 <<======
        objectMapper.writeValueAsString(new Person1("name", "password", null, Collections.emptyMap())); // {"my_name":"name"}
        objectMapper.readValue("{\"my_name\":\"lastname\", \"foo\":{\"bar\": 20}}", Person1.class); // Main.Person1(myName=lastname, password=null, nullIgnore=null, other={foo={bar=20}})
        // UnrecognizedPropertyException: Unrecognized field "myName"
        // objectMapper.readValue("{\"myName\":\"myname\"}", Person.class);

        // ======>> Person2 <<======
        objectMapper.writeValueAsString(new Person2("name", 20)); // {"name":"name","age":20}

        // ======>> Person3 <<======
        objectMapper.writeValueAsString(new Person3("name", "ignore")); // {"name":"name"}
    }

    @NoArgsConstructor @AllArgsConstructor @ToString
    @JsonInclude(JsonInclude.Include.NON_NULL)
    static class Person1 {
        @JsonProperty(value = "", required = false, index = -1, defaultValue = "")
        public String myName;
        @JsonIgnore(value = true)
        public String password;
        public String nullIgnore;

        protected Map<String, Object> other = new HashMap<String, Object>();

        // alternate for @JsonRawValue
        @JsonAnyGetter
        public Map<String, Object> any() {
            return other;
        }

        @JsonAnySetter
        public void set(String name, Object value) {
            other.put(name, value);
        }
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
    static class Person2 {
        public String name;
        private int age;
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @JsonIgnoreProperties(value = {"ignore"})
    static class Person3 {
        public String name;
        public String ignore;
    }
}
広告を非表示にする