import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.PackageVersion;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
/**
* json/XML处理类
*/
public final class SerializeUtil {
private SerializeUtil() {
throw new IllegalStateException("Utility class");
}
//region 字符串常量
private static final String TITLE = "SerializeUtil";
//endregion
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
private static final XmlMapper XML_MAPPER = new XmlMapper();
static {
//忽略字段大小写
XML_MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
//忽略字段数量不一致
XML_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//默认json序列化设置
SerializeUtil.initSerializationConfigure(JSON_MAPPER);
}
/**
* 默认json序列化设置
* @param JSON_MAPPER mapper实例
*/
private static void initSerializationConfigure(ObjectMapper JSON_MAPPER) {
//忽略字段大小写
JSON_MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
//此配置反序列化的时候如果多了属性, 不抛出异常。不设置这个json字符串只能少属性,不能多属性,否者会抛异常
JSON_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//如果是空对象的时候,不抛异常
JSON_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//******************************* 处理日期类型序列化和反序列化 *******************************
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
JSON_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
SimpleModule serializerModule = new SimpleModule("CQDateTimeSerializer", PackageVersion.VERSION);
serializerModule.addSerializer(Date.class, new CQDateSerializer());
serializerModule.addDeserializer(Date.class, new CQDateDeSerializer());
serializerModule.addSerializer(Calendar.class, new CQCalendarSerializer());
serializerModule.addDeserializer(Calendar.class, new CQCalendarDeSerializer());
serializerModule.addSerializer(LocalDate.class, new CQLocalDateSerializer());
serializerModule.addDeserializer(LocalDate.class, new CQLocalDateDeSerializer());
serializerModule.addSerializer(LocalDateTime.class, new CQLocalDateTimeSerializer());
serializerModule.addDeserializer(LocalDateTime.class, new CQLocalDateTimeDeSerializer());
serializerModule.addSerializer(Timestamp.class, new CQTimestampSerializer());
serializerModule.addDeserializer(Timestamp.class, new CQTimestampDeSerializer());
JSON_MAPPER.registerModule(serializerModule);
//******************************* 处理日期类型序列化和反序列化 *******************************
/*
//序列化的时候序列对象的所有属性
JSON_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
*/
}
/**
* json字符串转 T 类型实体
* @param json json字符串
* @param clazz 实体类型
* @param <T> 实体类型
*/
public static <T> T toObject(String json, Class<T> clazz) {
if(StringUtil.isNullOrEmpty(json)){
return null;
}
try {
if(Objects.equals(clazz, JsonObject.class)) {
JsonParser jsonParser = new JsonParser();
return (T)jsonParser.parse(json).getAsJsonObject();
}
return JSON_MAPPER.readValue(json, clazz);
} catch (IOException e) {
//TODO log
throw new RuntimeException(e);
}
}
/**
* json字符串转 List→T 类型集合
* @param json json字符串
* @param clazz 实体类型
* @param <T> 实体类型
*/
public static <T> List<T> toListObject(String json, Class<T> clazz){
if(StringUtil.isNullOrEmpty(json)){
return new ArrayList<>();
}
try{
//这种返回的是List<LinkedMap>
//return JSON_MAPPER.readValue(json, new TypeReference<List<T>>() {});
return SerializeUtil.toObject(json, List.class, clazz);
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
/**
* json字符串转 T 类型实体
* @param json json字符串
* @param genericClass 实体类型
* @param clazz 实体类型
* @param <T> 实体类型
*/
public static <T> T toObject(String json, Class<?> genericClass, Class<?> clazz) {
if(StringUtil.isNullOrEmpty(json)){
return null;
}
try {
JavaType type = JSON_MAPPER.getTypeFactory().constructParametricType(genericClass, clazz);
return JSON_MAPPER.readValue(json, type);
} catch (IOException e) {
//TODO log
throw new RuntimeException(e);
}
}
public static String toJson(Object obj) {
if(obj==null){
return null;
}
try {
if(obj instanceof JsonObject || obj instanceof JsonArray) {
return obj.toString();
} else {
return JSON_MAPPER.writeValueAsString(obj);
}
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static String toJsonWithoutNull(Object obj) {
if(obj==null){
return null;
}
try {
if (obj instanceof JsonObject || obj instanceof JsonArray) {
return obj.toString();
} else {
ObjectMapper mapper = new ObjectMapper();
//默认json序列化设置
SerializeUtil.initSerializationConfigure(mapper);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(obj);
}
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static String toCSharpJson(Object obj) {
if(obj==null){
return null;
}
try {
if (obj instanceof JsonObject || obj instanceof JsonArray) {
return obj.toString();
} else {
ObjectMapper mapper = new ObjectMapper();
//默认json序列化设置
SerializeUtil.initSerializationConfigure(mapper);
// deprecated mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
return mapper.writeValueAsString(obj);
}
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static String toJson(Object obj, String dateFormat) {
if(obj==null){
return null;
}
try {
if (obj instanceof JsonObject || obj instanceof JsonArray) {
return obj.toString();
} else {
ObjectMapper mapper = new ObjectMapper();
//默认json序列化设置
SerializeUtil.initSerializationConfigure(mapper);
mapper.setDateFormat(new SimpleDateFormat(dateFormat));
return mapper.writeValueAsString(obj);
}
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static <T> T fromXml(String xml, Class<T> clazz) {
if(StringUtil.isNullOrEmpty(xml)){
return null;
}
try {
return XML_MAPPER.readValue(xml, clazz);
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static <T> T fromXml(String xml, Class<?> genericClass, Class<?> clazz) {
if(StringUtil.isNullOrEmpty(xml)){
return null;
}
try {
JavaType type = XML_MAPPER.getTypeFactory().constructParametricType(genericClass, clazz);
return XML_MAPPER.readValue(xml, type);
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static String toXml(Object obj) {
if(obj == null){
return "";
}
try{
return XML_MAPPER.writeValueAsString(obj);
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
public static JsonObject toJSONObject(Object obj) {
if(null==obj) {
return null;
}
try {
String json = new Gson().toJson(obj);
return new JsonParser().parse(json).getAsJsonObject();
} catch (Exception e) {
//TODO log
throw new RuntimeException(e);
}
}
}
引入依赖
<!-- begin json序列化 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-protobuf</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- end json序列化 -->