io.castled.utils.JsonUtils Maven / Gradle / Ivy
package io.castled.utils;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.Maps;
import io.castled.exceptions.CastledRuntimeException;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonValue;
import java.io.IOException;
import java.util.Map;
public class JsonUtils {
public static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.registerModule(new JavaTimeModule());
}
public static T byteArrayToObject(byte[] value, Class clazz) {
try {
return objectMapper.readValue(value, clazz);
} catch (IOException e) {
throw new CastledRuntimeException(e);
}
}
public static T jsonStringToTypeReference(String jsonString, TypeReference typeReference) {
try {
return objectMapper.readValue(jsonString, typeReference);
} catch (JsonProcessingException e) {
throw new CastledRuntimeException(e);
}
}
public static Map jsonStringToMap(String jsonString) {
try {
return objectMapper.readValue(jsonString, new TypeReference