问题
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.
回答1:
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}
来源:https://stackoverflow.com/questions/24697808/globally-ignore-class-in-jackson