
com.vincentbrison.openlibraries.android.dualcache.JsonSerializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dualcache-jsonserializer Show documentation
Show all versions of dualcache-jsonserializer Show documentation
Json serializer for Android Dual Cache
The newest version!
package com.vincentbrison.openlibraries.android.dualcache;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
/**
* Serializer which will serialize and deserialize object using Jackson
* converter.
* @param is the class of object to serialize/deserialize.
*/
public class JsonSerializer implements CacheSerializer {
private final ObjectMapper mapper;
private final Class clazz;
/**
* Default constructor.
* @param clazz is the class of object to serialize/deserialize.
*/
public JsonSerializer(Class clazz) {
this.clazz = clazz;
mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
}
@Override
public T fromString(String data) {
try {
return mapper.readValue(data, clazz);
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException();
}
@Override
public String toString(T object) {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
throw new IllegalStateException();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy