简体   繁体   中英

Globally ignore class in Jackson

Jackson has ability to skip unknow properties globally using DeserializationFeature , but I can't find any global config to ignore whole class from being parsed. I have class with two methods with the same name but with different arguments, so I want to set this class as ignorable globally(using objectMapper object) not just by adding any annotations to model class. May be someone faced with such problem.

Sorry for bad English.

One option is to mark the type you wish to ignore with @JsonIgnoreType annotation. If you don't want to mess your model with Jackson annotations you can use mix-ins .

Another option is to override the Jackson annotation introspector to ignore the property based on its type.

Here is example shows both:

public class JacksonIgnoreByType {
    public static final String JSON = "{\n" +
            "  \"bean1\" : {\n" +
            "    \"field1\" : \"value1\"\n" +
            "  },\n" +
            "  \"bean2\" : {\n" +
            "    \"field2\" : \"value2\"\n" +
            "  },\n" +
            "  \"bean3\" : {\n" +
            "    \"field3\" : \"value3\"\n" +
            "  }\n" +
            "}\n";

    public static class Bean1 {
        public String field1;

        @Override
        public String toString() {
            return "Bean1{" +
                    "field1='" + field1 + '\'' +
                    '}';
        }
    }

    @JsonIgnoreType
    public static class Bean2 {
        public String field2;
    }

    public static class Bean3 {
        public String field3;
    }

    public static class Bean4 {
        public Bean1 bean1;
        public Bean2 bean2;
        public Bean3 bean3;

        @Override
        public String toString() {
            return "Bean4{" +
                    "bean1=" + bean1 +
                    ", bean2=" + bean2 +
                    ", bean3=" + bean3 +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector(){
            @Override
            public boolean hasIgnoreMarker(AnnotatedMember m) {
                return m.getRawType() == Bean3.class || super.hasIgnoreMarker(m);
            }
        });

        System.out.println(mapper.readValue(JSON, Bean4.class));
    }
}

Output:

Bean4{bean1=Bean1{field1='value1'}, bean2=null, bean3=null}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM