Search code examples
javajsonspring-dataspring-data-redisjackson2

Spring Redis JSON serializer embeds referenced field


I have a class which has many simple attributes (type is int,String,...). It also has an attribute which is an instance of another class of mine. Now I want to send the object via a Redis pub/sub channel. To do this I serialize it with the GenericJackson2JsonRedisSerializer. As both classes have their own repository I don't want to embed the object every time but instead only send the ID. I thought that this should be possible by adding the org.springframework.data.annotation.Reference annotation to the field.

Unfortunately this didn't work, instead it just embeds the object. Is there anything I did wrong? What do I have to do to just get the object's ID in the serialized version?

Thank you for your help!


Solution

  • Alright after way too much research for such a basic thing I finally figured out how to do it.

    Basically I needed to add the com.fasterxml.jackson.annotation.JsonIdentityInfo annotation to the class or field. As already stated in the question this produced the same result, first time completely included, afterwards only referenced.

    No documentation mentioned how to always have the id, I had to look into the code: there's another annotation com.fasterxml.jackson.annotation.JsonIdentityReference which has a boolean property called alwaysAsId. If you set this one to true it always adds the id instead of the object.

    To get the deserializing working one needs to specify a custom resolver for the ids. As I'm using Spring it has been quite easy to get access to my repository.