我使用redis缓存并面临这样的问题:带整数键的map被序列化为字符串,如下所示:
"1":"AAAA","2":"BBB","3":"CCC"我的配置如下所示:
@Bean
public RedisCacheConfiguration myCacheConfiguration()
{
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ZERO)
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new Jackson2JsonRedisSerializer<>(Map.class)));
}
@Bean
public CacheManager myCacheManager(RedisConnectionFactory redisConnectionFactory)
{
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(myCacheConfiguration())
.transactionAware()
.build();
}我试图将GenericJackson2JsonRedisSerializer传递给serializeValuesWith(),但无法工作。是否有任何方法将映射的整数键序列化为number?
发布于 2019-03-22 09:46:10
通过在JavaType中添加重写方法getJavaType(Class clazz),可以很容易地解决这个问题。文件上说:
/**
* Returns the Jackson {@link JavaType} for the specific class.
* <p>
* Default implementation returns {@link TypeFactory#constructType(java.lang.reflect.Type)}, but this can be
* overridden in subclasses, to allow for custom generic collection handling. For instance:
*
* <pre class="code">
* protected JavaType getJavaType(Class<?> clazz) {
* if (List.class.isAssignableFrom(clazz)) {
* return TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, MyBean.class);
* } else {
* return super.getJavaType(clazz);
* }
* }
* </pre>
*
* @param clazz the class to return the java type for
* @return the java type
*/
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}所以,我只是像这样覆盖这个方法:
public class CustomSerializer extends Jackson2JsonRedisSerializer
{
public JurisdictionsSerializer(Class type)
{
super(type);
}
@Override
protected JavaType getJavaType(Class clazz)
{
return TypeFactory.defaultInstance()
.constructMapType(Map.class, Integer.class, String.class);
}
}然后将这个序列化程序添加到redis配置中,如下所示:
@Bean
public RedisCacheConfiguration myCacheConfiguration()
{
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ZERO)
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new CustomSerializer(Map.class)));
}发布于 2019-03-21 10:58:13
Jackson2JsonRedisSerializer和GenericJackson2JsonRedisSerializer都允许使用自定义ObjectMapper。
不熟悉Redis,但根据文档,这似乎是定制序列化的设计方法
设置自定义的
ObjectMapper是进一步控制JSON序列化过程的一种方法。例如,可以配置扩展的SerializerFactory,为特定类型提供自定义序列化程序。细化序列化过程的另一个选项是使用Jackson提供的对要序列化的类型的注释,在这种情况下,没有必要使用自定义配置的ObjectMapper。
https://stackoverflow.com/questions/55278446
复制相似问题