我有一个接口(interface)(已经包含 Jackson 注释):
interface Interface {
@JsonValue
String fieldA();
String fieldB();
}
我无法修改,以及实现此接口(interface)的类:
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
类时,我希望生成的 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.
问题来自于接口(interface)上已经存在的 @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)])
有什么办法可以实现这一点吗?
最佳答案
访问the docs ,您应该能够在子类中设置“false”JSON 值:
Boolean argument is only used so that sub-classes can "disable" annotation if necessary.
我想这已经告诉了你需要知道的一切,但它看起来像这样:
class Impl implements Interface {
//...
@Override
@JsonSerialize
@JsonValue(false) //...disables inherited annotation
public String fieldA() {
return fieldA;
}
// ...
}
关于java - 从父类(super class)覆盖 jackson @JsonValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902667/