com.nepxion.discovery.common.util.JsonUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of discovery-common Show documentation
Show all versions of discovery-common Show documentation
Nepxion Discovery is an enhancement for Spring Cloud Discovery
package com.nepxion.discovery.common.util;
/**
* Title: Nepxion Discovery
* Description: Nepxion Discovery
* Copyright: Copyright (c) 2017-2050
* Company: Nepxion
* @author Haojun Ren
* @version 1.0
*/
import java.text.SimpleDateFormat;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
}
public static String toJson(T object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static T fromJson(String json, Class clazz) {
if (StringUtils.isEmpty(json)) {
throw new IllegalArgumentException("Json is null or empty");
}
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static T fromJson(String json, TypeReference typeReference) {
if (StringUtils.isEmpty(json)) {
throw new IllegalArgumentException("Json is null or empty");
}
try {
return objectMapper.readValue(json, typeReference);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy