package org.jeecg.modules.dnc.utils;
|
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
|
import java.text.SimpleDateFormat;
|
|
public class JsonUtils {
|
private static final ObjectMapper objectMapper = createObjectMapper();
|
|
private static ObjectMapper createObjectMapper() {
|
ObjectMapper mapper = new ObjectMapper();
|
|
// 配置日期格式
|
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
|
mapper.registerModule(new JavaTimeModule());
|
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
|
// 配置序列化选项
|
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
|
// 配置反序列化选项
|
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
|
mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
|
|
return mapper;
|
}
|
|
public static String toJson(Object object) {
|
try {
|
return objectMapper.writeValueAsString(object);
|
} catch (Exception e) {
|
throw new RuntimeException("JSON序列化失败: " + e.getMessage(), e);
|
}
|
}
|
|
public static <T> T fromJson(String json, Class<T> valueType) {
|
try {
|
return objectMapper.readValue(json, valueType);
|
} catch (Exception e) {
|
throw new RuntimeException("JSON反序列化失败: " + e.getMessage() + "\nJSON内容: " + json, e);
|
}
|
}
|
}
|