全球忽略杰克逊的课程 [英] Globally ignore class in Jackson
问题描述
Jackson能够使用 DeserializationFeature
全局跳过未知属性,但是我找不到任何全局配置来忽略整个类的解析.我有两个具有相同名称但具有不同参数的方法的类,因此我想将此类设置为全局可忽略的(使用objectMapper对象),而不仅仅是在模型类中添加任何注释.可能有人遇到这样的问题.
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.
对不起,英语不好.
推荐答案
一个选项是使用@JsonIgnoreType注释标记要忽略的类型.如果您不想让Jackson注释弄乱模型,可以使用混合插件.
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.
另一种选择是覆盖 Jackson注释内省器,以根据其类型忽略该属性.
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));
}
}
输出:
Bean4{bean1=Bean1{field1='value1'}, bean2=null, bean3=null}
这篇关于全球忽略杰克逊的课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!