Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Jackson serialization when using value objects as entity id

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.

like image 980
Wim Deblauwe Avatar asked Dec 08 '15 10:12

Wim Deblauwe


1 Answers

Use @JsonUnwrapped. It works perfectly with objects with a single property, too, IIRC.

like image 192
GeertPt Avatar answered Oct 15 '22 08:10

GeertPt