I want to use a Value Object as the database id in my entity. I also want to have clean 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:
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). I could write serializers and deserializers for each Entity, but I was hoping on a more generic solution.
Use @JsonUnwrapped. It works perfectly with objects with a single property, too, IIRC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With