org.kaizen4j.common.util.JsonUtils Maven / Gradle / Ivy
package org.kaizen4j.common.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
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.google.common.base.Throwables;
import java.io.IOException;
import java.io.StringWriter;
public final class JsonUtils {
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
public static String getJson(Object obj) {
StringWriter stringWriter = new StringWriter();
try {
getObjectMapper().writeValue(stringWriter, obj);
} catch (IOException e) {
throw new RuntimeException(e);
}
return stringWriter.toString();
}
public static T readValue(String content, Class clazz) {
try {
return getJsonParser(content).readValueAs(clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static T readValue(String content, TypeReference typeReference) {
try {
return getJsonParser(content).readValueAs(typeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static JsonParser getJsonParser(String content) throws IOException {
JsonFactory jsonFactory = getObjectMapper().getFactory();
JsonParser jsonParser = jsonFactory.createParser(content);
jsonParser.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
return jsonParser;
}
public static JsonNode readValue(String content) {
return readValue(content, JsonNode.class);
}
}