Jack工具类
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
@Slf4j
public final class JsonUtil {
private static ObjectMapper MAPPER = new ObjectMapper();
private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
static {
MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
private JsonUtil() {
}
public static String toJson(Object object) {
if (object == null) {
return null;
}
try {
return object instanceof String ? (String) object : MAPPER.writeValueAsString(object);
} catch (Exception e) {
log.error("method=toJson() is convert error, errorMsg:{}", e.getMessage(), e);
return null;
}
}
public static String toJsonEmpty(Object object) {
if (object == null) {
return null;
}
try {
MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object param, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
return MAPPER.writeValueAsString(object);
} catch (Exception e) {
log.error("method=toJsonEmpty() is convert error, errorMsg:{}", e.getMessage(), e);
}
return null;
}
public static <T> T fromJSON(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text) || clazz == null) {
return null;
}
try {
return MAPPER.readValue(text, clazz);
} catch (Exception e) {
log.error("method=toBean() is convert error, errorMsg:{}", e.getMessage(), e);
}
return null;
}
public static <K, V> Map<K, V> toMap(String text) {
try {
if (StringUtils.isEmpty(text)) {
return null;
}
return toObject(text, new TypeReference<Map<K, V>>() {
});
} catch (Exception e) {
log.error("method=toMap() is convert error, errorMsg:{}", e.getMessage(), e);
}
return null;
}
public static <T> List<T> toList(String text) {
if (StringUtils.isEmpty(text)) {
return null;
}
try {
return toObject(text, new TypeReference<List<T>>() {
});
} catch (Exception e) {
log.error("method=toList() is convert error, errorMsg:{}", e.getMessage(), e);
}
return null;
}
public static <T> T toObject(String text, TypeReference<T> typeReference) {
try {
if (StringUtils.isEmpty(text) || typeReference == null) {
return null;
}
return (T) (typeReference.getType().equals(String.class) ? text : MAPPER.readValue(text, typeReference));
} catch (Exception e) {
log.error("method=toObject() is convert error, errorMsg:{}", e.getMessage(), e);
}
return null;
}
}