argos/dmp-backend/src/main/java/helpers/SerializerProvider.java

84 lines
2.4 KiB
Java

package helpers;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module.Feature;
public class SerializerProvider {
private static ObjectMapper objectMapper = null;
static {
initialize();
}
public static void initialize() {
Hibernate5Module module = new Hibernate5Module();
//module.enable(Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
objectMapper = new ObjectMapper()
//.setSerializationInclusion(Include.NON_NULL)
//.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(module)
;
}
public static CollectionType constructTypeFor(Class<? extends Collection> collectionClass, Class<?> elementClass) {
return objectMapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
}
public static ObjectMapper getJsonSerializer() {
if(objectMapper==null)
initialize();
return objectMapper;
}
public static String toJson(Object obj) {
try {
return getJsonSerializer().writeValueAsString(obj);
}catch(JsonProcessingException ex) {
return "";
}
}
public static String toJson(Collection<?> coll) {
List<String> list = coll.parallelStream().map(obj -> toJson(obj)).collect(Collectors.toList());
return "["+StringUtils.join(list.toArray(), ",")+"]";
}
public static <T> T fromJson(String jsonObject, Class<T> type) throws Exception {
return getJsonSerializer().readValue(jsonObject, type);
}
public static <T> T fromJson(String jsonObject, JavaType type) throws Exception {
return getJsonSerializer().readValue(jsonObject, type);
}
public static <T> T fromJson(String jsonObject, TypeReference typeRef) throws Exception {
return getJsonSerializer().readValue(jsonObject, typeRef);
}
}