Neo
Neo

Reputation: 2226

Spring cache with Redis using Jackson serializer: How to deal with multiple type of domain object

There are many types of domain objects in my web application, such as MemberModel, PostModel, CreditsModel and so on. I find that the type of the object is needed when configuring JacksonJsonRedisSerializer, so I specified Object.class. But I got error when deserializing objects.

To work around this, I've got 2 options:

Is there a graceful way to solve this problem? Thanks!

Upvotes: 5

Views: 4687

Answers (1)

Christoph Strobl
Christoph Strobl

Reputation: 6736

There's an open PR #145 available. Untill that one is merged one can pretty much just implement a RedisSerializer the way it is done in GenericJackson2JsonRedisSerializer configuring the used ObjectMapper to inlcude type information within the json.

ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);

byte[] bytes = mapper.writeValueAsBytes(domainObject);

// using Object.class allows the mapper fall back to the default typing.
// one could also use a concrete domain type if known to avoid the cast.
DomainObject target = (DomainObject) mapper.readValue(bytes, Object.class);

Upvotes: 5

Related Questions