[英]Override jackson @JsonValue from superclass
我有一个接口(已经包含一个 Jackson 注释):
interface Interface {
@JsonValue
String fieldA();
String fieldB();
}
我无法修改,以及实现此接口的 class :
class Impl implements Interface {
String fieldA;
String fieldB;
public Impl(String fieldA, String fieldB) {
this.fieldA = fieldA;
this.fieldB = fieldB;
}
@Override
@JsonSerialize
public String fieldA() {
return fieldA;
}
@Override
@JsonSerialize
public String fieldB() {
return fieldB;
}
}
现在,当我序列化Impl
class 时,我希望生成的 Json 将同时存在两个字段( fieldA
和fieldB
)。
不是这种情况:
@Test
void should_serialize_both_fields() throws JsonProcessingException {
// Given
ObjectMapper mapper = new ObjectMapper();
Impl example = new Impl("test", "test");
String expected = "{\"fieldA\": \"test\", \"fieldB\": \"test\"}";
// When
String json = mapper.writeValueAsString(example);
// Then
org.assertj.core.api.Assertions.assertThat(json).isEqualTo(expected);
}
在此测试中,生成的json
是"test"
而不是{"fieldA": "test", "fieldB": "test"}
:
org.opentest4j.AssertionFailedError:
Expecting:
<""test"">
to be equal to:
<"{"fieldA": "test", "fieldB": "test"}">
but was not.
问题来自接口上已经存在的@JsonValue
注释,我无法修改。 另外,如果我尝试在Impl
中注释另一个方法,那么我会从 jackson 得到这个异常:
com.fasterxml.jackson.databind.JsonMappingException: Problem with definition of [AnnotedClass com.actility.m2m.commons.service.error.InternalErrorCodeImplTest$Impl]: Multiple 'as-value' properties defined ([method com.actility.m2m.commons.service.error.InternalErrorCodeImplTest$Impl#fieldB(0 params)] vs [method com.actility.m2m.commons.service.error.InternalErrorCodeImplTest$Impl#fieldA(0 params)])
有什么办法可以做到这一点?
按照文档,您应该能够在子类中设置“假” JSON 值:
Boolean 参数仅用于子类可以在必要时“禁用”注释。
我想这已经告诉了你所有你需要知道的,但它看起来像这样:
class Impl implements Interface {
//...
@Override
@JsonSerialize
@JsonValue(false) //...disables inherited annotation
public String fieldA() {
return fieldA;
}
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.