[英]Jackson object mapper how to ignore JsonProperty annotation?
I have the following scenario:我有以下场景:
public class A {
@JsonProperty("member")
private Integer Member;
}
public class B {
private Integer Member;
}
Now, I wish to do the following:现在,我希望执行以下操作:
ObjectMapper mapper = new ObjectMapper();
B b = new B(); b.setMember(1);
A a = mapper.converValue(b, A.class);
Ordinarily, this would work.通常,这会起作用。 However, since the
objectMapper
takes annotations such as @JsonProperty
into account, I get the following result:然而,由于
objectMapper
需要注释,比如@JsonProperty
考虑,我得到以下结果:
A.getMember(); // Member = NULL
There is a workaround, where all fields that are expected to be null
due to this are set manually, ie A.setMember(b.getMember());
有一种解决方法,即手动设置所有预期为
null
字段,即A.setMember(b.getMember());
, but this defeats the purpose of using the objectMapper
in the first place and is potentially error-prone. ,但这首先违背了使用
objectMapper
的目的,并且可能容易出错。
Is there a way to configure the objectMapper
to ignore the @JsonProperty
fields of a given class (or globally)?有没有办法配置
objectMapper
以忽略给定类(或全局)的@JsonProperty
字段?
You can configure the ObjectMapper to ignore annotations like @JsonProperty by doing:您可以通过执行以下操作将 ObjectMapper 配置为忽略 @JsonProperty 之类的注释:
ObjectMapper objectMapper = new ObjectMapper().configure(
org.codehaus.jackson.map.DeserializationConfig.Feature.USE_ANNOTATIONS, false)
.configure(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, false)
But this will cause it to also ignore things like @JsonIgnore etc. I'm not aware of any way to make the ObjectMapper ignore only specific annotations.但这会导致它也忽略@JsonIgnore 等内容。我不知道有什么方法可以让 ObjectMapper 只忽略特定的注释。
To ignore all annotations the syntax in Jackson version 2.x is:要忽略所有注释,Jackson 2.x 版中的语法是:
objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false)
Just ignoring a subset seems to be not possible with this approach.使用这种方法似乎不可能仅仅忽略一个子集。
But a much better solution can be found in this answer: https://stackoverflow.com/a/55064740/3351474但是在这个答案中可以找到更好的解决方案: https : //stackoverflow.com/a/55064740/3351474
For your needs it should be then:根据您的需要,它应该是:
public static class IgnoreJacksonPropertyName extends JacksonAnnotationIntrospector {
@Override
protected <A extends Annotation> A _findAnnotation(Annotated annotated, Class<A> annoClass) {
if (annoClass == JsonProperty.class) {
return null;
}
return super._findAnnotation(annotated, annoClass);
}
}
...
mapper.setAnnotationIntrospector(new IgnoreJacksonPropertyName());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.