ObjectMapper provide writerWithView method for controlling which property to be serialize this make us able to adjust and make sure which properties written to the cache server
for example
public class User {
@JsonView(Views.Basic.class)
public int id;
@JsonView(Views.Basic.class)
public String name;
@JsonView(Views.Detailed.class)
public String email;
@JsonView(Views.Detailed.class)
public String mobile;
}
public class Views {
public static class Basic {
}
public static class Detailed {
}
public static class ViewBasic extends Basic{
}
public static class ViewDetailed extends ViewBasic , Detailed {
}
}
so if we want to cache only id,name we only pass ViewBasic to the WriterView
for example
objectMapper.writerWithView(Views.ViewBasic.class).writeValueAsBytes(user)
if we need basic+email,mobile we should pass ViewDetailed to the WriterView
easy fix
we could override GenericJackson2JsonRedisSerializer.serialize
with this code
@Override
public byte[] serialize(Object source) throws SerializationException {
if (source == null) {
return EMPTY_ARRAY;
}
try {
if (source instanceof CacheView) {
CacheView cacheView = (CacheView) source;
return cachingObjectMapper.writerWithView(cacheView.getCacheView()).writeValueAsBytes(source);
} else {
return cachingObjectMapper.writeValueAsBytes(source);
}
} catch (JsonProcessingException e) {
throw new SerializationException("Could not write JSON: " + e.getMessage(), e);
}
}
import com.fasterxml.jackson.annotation.JsonIgnore;
public interface CacheView {
@JsonIgnore
Class<?> getCacheView();
}
public class User implements Serializable, CacheView{
@JsonView(Views.Basic.class)
public int id;
@JsonView(Views.Basic.class)
public String name;
@JsonView(Views.Detailed.class)
public String email;
@JsonView(Views.Detailed.class)
public String mobile;
private Class<?> cacheView;
}
ObjectMapper provide
writerWithViewmethod for controlling which property to be serialize this make us able to adjust and make sure which properties written to the cache serverfor example
so if we want to cache only
id,namewe only passViewBasicto theWriterViewfor example
if we need basic+
email,mobilewe should passViewDetailedto theWriterVieweasy fix
we could override
GenericJackson2JsonRedisSerializer.serializewith this code