[英]Customize Jackson serialization when using value objects as entity id
I want to use a Value Object as the database id in my entity.我想在我的实体中使用一个值对象作为数据库 ID。 I also want to have clean JSON.我也想要干净的 JSON。 Suppose I have this entity:假设我有这个实体:
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;
}
}
Which has this id class:其中有这个 id 类:
private static class TestEntityId extends ImmutableEntityId<Long> {
public TestEntityId(Long id) {
super(id);
}
}
If I use default settings of Jackson, I get this:如果我使用杰克逊的默认设置,我会得到这个:
{"id":{"id":1},"mutableProperty":"blabla"}
But I would like to get this:但我想得到这个:
{"id":1,"mutableProperty":"blabla"}
I managed to get the serialization ok by adding a custom serializer:通过添加自定义序列化程序,我设法使序列化正常:
addSerializer(ImmutableEntityId.class, new JsonSerializer<ImmutableEntityId>() {
@Override
public void serialize(ImmutableEntityId immutableEntityId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeNumber( (Long)immutableEntityId.getId() );
}
});
(I know that the cast is not really good, but please ignore that for the purpose of the question). (我知道演员阵容不是很好,但请出于问题的目的忽略这一点)。
The question is how can I write a deserializer for it?问题是我怎样才能为它编写一个解串器? Somehow Jackson should keep track that when deserializing a TestEntity
, he needs to create a TestEntityId
instance (and not the ImmutableEntityId
superclass).杰克逊应该以某种方式跟踪在反序列化TestEntity
,他需要创建一个TestEntityId
实例(而不是ImmutableEntityId
超类)。 I could write serializers and deserializers for each Entity, but I was hoping on a more generic solution.我可以为每个实体编写序列化器和反序列化器,但我希望有一个更通用的解决方案。
Use @JsonUnwrapped .使用@JsonUnwrapped 。 It works perfectly with objects with a single property, too, IIRC.它也适用于具有单一属性 IIRC 的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.