com.feingto.cloud.kit.json.JSONObjectMapper Maven / Gradle / Ivy
package com.feingto.cloud.kit.json;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.feingto.cloud.kit.ClassKit;
import com.feingto.cloud.kit.DateKit;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
/**
* Jackson ObjectMapper
*
* @author longfei
*/
@Slf4j
public class JSONObjectMapper extends ObjectMapper {
private static final long serialVersionUID = -2088277558896145073L;
public JSONObjectMapper() {
if (ClassKit.isExist("org.hibernate.proxy.HibernateProxy")) {
Hibernate5Module hibernate5Module = new Hibernate5Module();
hibernate5Module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);// 序列化不过滤 @Transient
hibernate5Module.enable(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
this.registerModule(hibernate5Module);// Register Hibernate5Module
} else {
log.info("No org.hibernate.proxy.HibernateProxy found");
}
this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);// 允许使用单引号(撇号,字符"\")引用的字符串(字符串名称和值)
this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);// 允许使用非挂牌字段名称
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);// 空对象不抛异常
// this.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);// 序列化枚举是以toString()来输出,默认false,即默认以name()来输出
// this.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);// 反序列化枚举是以toString()来输出,默认false,即默认以name()来输出
this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
this.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
}
/**
* 日期格式按照"yyyy-MM-dd HH:mm:ss"序列化
*/
public JSONObjectMapper useDateTime() {
this.setDateFormat(new SimpleDateFormat(DateKit.DATE_TIME));
this.setTimeZone(TimeZone.getDefault());
return this;
}
/**
* 日期格式按照ISO8601标准序列化, 使用UTC时间
*/
public JSONObjectMapper useUTC() {
this.setDateFormat(new SimpleDateFormat(DateKit.DATE_TIME_UTC));
this.setTimeZone(TimeZone.getTimeZone("UTC"));
return this;
}
}