preface

A background project that uses Spring Cache to serialize data to Redis has no problem, deserialization failed when read back

Error 1

Deserialization of LocalDateTime failed because LocalDateTime has no constructor

The solution

        Jackson2JsonRedisSerializer<Object> j2jrs = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        // Resolve a problem where Jackson2 cannot deserialize LocalDateTime
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
        j2jrs.setObjectMapper(om);
Copy the code

Error 2

LinkedHashMap cannot be converted to the specified object

Solution: Set defaultType

// Serialize the class name into the JSON string. Direct conversion entity object will fail om. ActivateDefaultTyping (LaissezFaireSubTypeValidator. Instance, ObjectMapper. DefaultTyping. NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);Copy the code

Note that the original enableDefaultTyping() method is out of date