
com.spikeify.converters.JsonConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of core Show documentation
Show all versions of core Show documentation
Simple ORM for Aerospike
package com.spikeify.converters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.spikeify.Converter;
import com.spikeify.SpikeifyError;
import java.io.IOException;
import java.lang.reflect.Field;
public class JsonConverter implements Converter {
private static final ThreadLocal tlObjectMapper = new ThreadLocal() {
@Override
protected ObjectMapper initialValue() {
return new ObjectMapper();
}
};
private final JavaType type;
public JsonConverter(Class type) {
this.type = TypeFactory.defaultInstance().constructType(type);
}
public JsonConverter(Field field) {
this.type = TypeFactory.defaultInstance().constructType(field.getGenericType());
}
@Override
public T fromProperty(String property) {
if (property == null) {
return null;
}
try {
return tlObjectMapper.get().readValue(property, type);
} catch (IOException e) {
throw new SpikeifyError("Error deserializing from JSON: ", e);
}
}
@Override
public String fromField(T fieldValue) {
try {
return tlObjectMapper.get().writeValueAsString(fieldValue);
} catch (JsonProcessingException e) {
throw new SpikeifyError("Error serializing to JSON: ", e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy