从超类重写Jackson @JsonValue

时间:2019-11-17 16:33:56

标签: java json jackson jackson-databind

我有一个接口(已经包含Jackson注释):

interface Interface {
    @JsonValue
    String fieldA();

    String fieldB();
}
我无法修改的

和实现此接口的类:

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将同时存在两个字段(fieldAfieldB)。

情况并非如此:

@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中注释另一个方法,那么我会从杰克逊得到这个异常:

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)])

有什么办法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

通过the docs,您应该能够在子类中设置“ false” JSON值:

  

仅使用布尔参数,以便子类在必要时可以“禁用”注释。

我想这已经告诉了您所有您需要知道的内容,但这就是它的样子:

class Impl implements Interface {
    //...

    @Override
    @JsonSerialize
    @JsonValue(false) //...disables inherited annotation
    public String fieldA() {
        return fieldA;
    }

    // ...
}