Home > Net >  Java Serializer and Deserializer for MongoDB and Redis
Java Serializer and Deserializer for MongoDB and Redis

Time:01-27

in the past, I used the Jackson annotation called @JsonSerialize and @JsonDeserialize to serialize java object to json and vice versa:

public class Dummy {

    @JsonSerialize(using = CustomNumberSerializer.class)
    @JsonDeserialize(using = CustomNumberDeserializer.class)
    public BigDecimal money;

    @JsonSerialize(using = CustomDateSerializer.class)
    @JsonDeserialize(using = CustomDateDeserializer.class)
    public Date eventDate;

}

and that works perfectly as I want.

Now I'm wondering if there is any alternative that does the same job, but during the calls to databases like MongoDB and Redis.

So for example:

BigDecimal money = new BigDecimal("1234.56");
Date eventDate = new Date();
Dummy dummy = new Dummy(money, eventDate);

Storing the dummy object into DB, I want to see the variables stored as String
money "1.234,56"
eventDate "25/01/2023"

when I query the db, I want that those strings are transformed back to their Type.
In this way, I can use a specific patter for each field.

Any documentation/tutorial about that would be really appreciated.

CodePudding user response:

In Springboot, we have used the RedisTemplate to connect to the redis instance running in the cloud. The RedisTemplate is configured as a custom bean in the spring configuration. There you have the option of adding a custom serializer/deserializer. We have used spring's GenericJackson2JsonRedisSerializer, this serializer includes the object's type names in the serialized string and this would help during deserialization.

If you want to add any custom logic during serialization and deserialization, you can extend this class and override the respective methods.

The custom serializer can then be added to the redis template using the following code.

@Bean
public RedisTemplate<String, Map<String, Object>> redisTemplateStandAlone(LettuceConnectionFactory redisConnectionFactory) {
    GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();             
    RedisTemplate<String, Map<String, Object>> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    redisTemplate.setKeySerializer(serializer);
    redisTemplate.setValueSerializer(serializer);         
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
}

In case of Mongo DB, I believe a similar concept can be applied using custom converters.

The following sample code shows how to configure custom converters in your mongo configuration in spring

  @Override
  public MongoCustomConversions customConversions() {
    List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
    converters.add(new CustomConverter());
    return new MongoCustomConversions(converters);
}

please refer to the following links for more information on the same

  • Related