com.github.shoothzj.javatool.service.JacksonService Maven / Gradle / Ivy
The newest version!
package com.github.shoothzj.javatool.service;
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.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.List;
/**
* @author akka
*/
public class JacksonService {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(JacksonService.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
}
public static String toJson(Object o) {
try {
return MAPPER.writeValueAsString(o);
} catch (Exception e) {
log.error("json process error, exception is ", e);
}
return "";
}
public static T toObject(String json, Class type) {
try {
return MAPPER.readValue(json, type);
} catch (Exception e) {
log.error("json process error, exception is ", e);
}
return null;
}
public static T toRefer(String json, TypeReference reference) {
try {
return MAPPER.readValue(json, reference);
} catch (Exception e) {
return null;
}
}
public static List toList(String json, TypeReference> typeReference) {
try {
return MAPPER.readValue(json, typeReference);
} catch (Exception e) {
return null;
}
}
public static JsonNode toJsonNode(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
return null;
}
}
public static ObjectNode createObjectNode() {
return MAPPER.createObjectNode();
}
public static ArrayNode createArrayNode() {
return MAPPER.createArrayNode();
}
}