public class JsonUtil {
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static ObjectMapper objectMapper = new ObjectMapper();
static{
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
}
/**
* Object对象转换成Json字符串
* @param object
* @return
*/
public static String ObjectToString(Object object){
try{
return objectMapper.writeValueAsString(object);
}catch(Exception e){
logger.error("Convert object to string error, object={}, msg={}, cause={}",object, e.getMessage(), e.getCause());
throw new JsonConvertException(e.getMessage(), e.getCause());
}
}
/**
* Json字符串转换成Object对象
* @param json
* @param type
* @param <T>
* @return
*/
public static <T> T StringToObject(String json, Class<T> type){
try{
return objectMapper.readValue(json, type);
}catch(Exception e){
logger.error("Convert string to object error, string={}, msg={}, cause={}", json, e.getMessage(), e.getCause());
throw new JsonConvertException(e.getMessage(), e.getCause());
}
}
}