使用值对象作为实体 id 时自定义 Jackson 序列化

Wim*_*uwe 6 java serialization json

我想在我的实体中使用一个值对象作为数据库 ID。我也想要干净的 JSON。假设我有这个实体:

private static class TestEntity {
    private TestEntityId id;
    private String mutableProperty;

    public TestEntity(TestEntityId id) {
        this.id = id;
    }

    public TestEntityId getId() {
        return id;
    }

    public String getMutableProperty() {
        return mutableProperty;
    }

    public void setMutableProperty(String mutableProperty) {
        this.mutableProperty = mutableProperty;
    }
}
Run Code Online (Sandbox Code Playgroud)

其中有这个 id 类:

private static class TestEntityId extends ImmutableEntityId<Long> {
    public TestEntityId(Long id) {
        super(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用杰克逊的默认设置,我会得到这个:

{"id":{"id":1},"mutableProperty":"blabla"}
Run Code Online (Sandbox Code Playgroud)

但我想得到这个:

{"id":1,"mutableProperty":"blabla"}
Run Code Online (Sandbox Code Playgroud)

通过添加自定义序列化程序,我设法使序列化正常:

        addSerializer(ImmutableEntityId.class, new JsonSerializer<ImmutableEntityId>() {
            @Override
            public void serialize(ImmutableEntityId immutableEntityId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeNumber( (Long)immutableEntityId.getId() );
            }
        });
Run Code Online (Sandbox Code Playgroud)

(我知道演员阵容不是很好,但请出于问题的目的忽略这一点)。

问题是我怎样才能为它编写一个解串器?杰克逊应该以某种方式跟踪在反序列化 a 时TestEntity,他需要创建一个TestEntityId实例(而不是ImmutableEntityId超类)。我可以为每个实体编写序列化器和反序列化器,但我希望有一个更通用的解决方案。

Gee*_*nte 5

使用@JsonUnwrapped。它也适用于具有单一属性的对象,IIRC。