我使用Jackson(2.1.1)进行JSON序列化/反序列化.我有一个带有JAXB注释的现有类.大多数这些注释都是正确的,可以和杰克逊一样使用.我正在使用mix-ins来稍微改变这些类的反序列化/序列化.
在我的ObjectMapper构造函数中,我执行以下操作:
setAnnotationIntrospector(AnnotationIntrospector.pair(
new JacksonAnnotationIntrospector(),
new JaxbAnnotationIntrospector(getTypeFactory())));
Run Code Online (Sandbox Code Playgroud)
基于以上所述,杰克逊注释优先于Jaxb,因为内省人的顺序.这是基于杰克逊Jaxb 文档.对于我想要忽略@JsonIgnore的字段,添加到混合中的字段工作正常.有几个字段标记为@XmlTransient现有类中我不想忽略的字段.我已经尝试@JsonProperty在混合中添加到该字段,但它似乎不起作用.
这是原始课程:
public class Foo {
@XmlTransient public String getBar() {...}
public String getBaz() {...}
}
Run Code Online (Sandbox Code Playgroud)
这是混合:
public interface FooMixIn {
@JsonIgnore String getBaz(); //ignore the baz property
@JsonProperty String getBar(); //override @XmlTransient with @JsonProperty
}
Run Code Online (Sandbox Code Playgroud)
知道如何在不修改原始类的情况下解决这个问题吗?
我还测试了将@JsonProperty添加到成员而不是使用mix-ins:
public class Foo {
@JsonProperty @XmlTransient public String getBar() {...}
@JsonIgnore public String getBaz() {...}
}
Run Code Online (Sandbox Code Playgroud)
我似乎得到了与混合输入相同的行为.除非删除@XmlTransient,否则将忽略该属性.
问题是,如果任何一个introspector检测到一个忽略标记,AnnotationIntrospectorPair.hasIgnoreMarker()方法基本上会忽略@JsonProperty:
public boolean hasIgnoreMarker(AnnotatedMember m) {
return _primary.hasIgnoreMarker(m) || _secondary.hasIgnoreMarker(m);
}
Run Code Online (Sandbox Code Playgroud)
ref:github
解决方法是子类化JaxbAnnotationIntrospector以获得所需的行为:
public class CustomJaxbAnnotationIntrospector extends JaxbAnnotationIntrospector {
public CustomJaxbAnnotationIntrospector(TypeFactory typeFactory) {
super(typeFactory);
}
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
if ( m.hasAnnotation(JsonProperty.class) ) {
return false;
} else {
return super.hasIgnoreMarker(m);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需使用AnnotationIntrospectorPair.hasIgnoreMarker()中@JsonProperty.
| 归档时间: |
|
| 查看次数: |
5087 次 |
| 最近记录: |