Skip to content

Instantly share code, notes, and snippets.

@martypitt
Created August 8, 2013 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martypitt/6184111 to your computer and use it in GitHub Desktop.
Save martypitt/6184111 to your computer and use it in GitHub Desktop.
Workaround for issues with Spring-Data-Redis Jackson's serializer, described here: http://forum.springsource.org/showthread.php?140744-Problems-with-Jackson-Redis-hash-mapping-of-nulls-amp-collections
package com.mangofactory.example;
import java.util.Map;
import lombok.SneakyThrows;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.data.redis.hash.JacksonHashMapper;
import com.google.common.collect.Maps;
/**
* Work-around to bug listed here:
* http://forum.springsource.org/showthread.php?140744-Problems-with-Jackson-Redis-hash-mapping-of-nulls-amp-collections&p=453090#post453090
*
* The {@link JacksonHashMapper} that ships with Spring Data Redis tries to map
* via jackson Object --> Hash<String,Object> --> Object
* However, this appears to fail.
*
* So, as a workaround, just write the object as pure JSON, and then decode it again.
* This gives the benefit of still using Jackson mappers (which give fine-grained, annotation
* driven control over the serialization process).
*
* @author martypitt
*
*/
public class StringBoundJsonHashMapper<T> implements HashMapper<T, String, String> {
private final ObjectMapper mapper;
private final JavaType userType;
private final JavaType mapType = TypeFactory.mapType(Map.class, String.class, String.class);
public StringBoundJsonHashMapper(Class<T> type) {
this(type, new ObjectMapper());
}
public StringBoundJsonHashMapper(Class<T> type, ObjectMapper mapper) {
this.mapper = mapper;
this.userType = TypeFactory.type(type);
}
@SuppressWarnings("unchecked") @SneakyThrows
public T fromHash(Map<String, String> hash) {
String json = hash.get("json");
T result = (T) mapper.readValue(json, userType);
return result;
}
@SneakyThrows
public Map<String, String> toHash(T object) {
String json = mapper.writeValueAsString(object);
Map<String,String> result = Maps.newHashMap();
result.put("json", json);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment