在Java里的Json序列化自定义日期格式。尤其是多语言环境里日期格式是不一样,导致无法兼容。
肥话少说,直接上代码。
源码如下:
public final class JacksonUtils {
private JacksonUtils() {
}
/**
* 单例注册Jackson
*/
private static class Singleton {
private static final JacksonUtils INSTANCE = new JacksonUtils();
private final static ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
MAPPER.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
MAPPER.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
MAPPER.configure(com.fasterxml.jackson.core.JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
MAPPER.configure(com.fasterxml.jackson.core.JsonParser.Feature.IGNORE_UNDEFINED, true);
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
MAPPER.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
MAPPER.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
/**
首先自定义简单序列化和反序列化解析模型,注册JackSon里。
*/
SimpleModule serializerModule = new SimpleModule("DateSerializer", PackageVersion.VERSION);
serializerModule.addSerializer(Calendar.class, new CustomCalendarSerializer());
serializerModule.addSerializer(Date.class, new CustomDateSerializer());
serializerModule.addDeserializer(Calendar.class, new CustomCalendarDeSerializer());
serializerModule.addDeserializer(Date.class, new CustomDateDeSerializer());
MAPPER.registerModule(serializerModule);
}
static class CustomCalendarSerializer extends CalendarSerializer {
@Override
public void serialize(Calendar value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(ExtensionUtils.parseCalendarToString(value, ExtensionUtils.LocalDateFormatEnum
.YYYY_MM_DD_HH_MM_SS));
}
}
static class CustomDateSerializer extends DateSerializer {
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(ExtensionUtils.parseDateToString(value, ExtensionUtils.LocalDateFormatEnum
.YYYY_MM_DD_HH_MM_SS));
}
}
static class CustomCalendarDeSerializer extends DateDeserializers.CalendarDeserializer {
@Override
public Calendar deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (p != null) {
String calendatStr = p.getText();
if (StringUtils.isNotBlank(calendatStr) && !StringUtils.contains(calendatStr, 'T') &&
calendatStr.length() == 19) {
LocalDateTime dateTime = LocalDateTime.parse(calendatStr, ExtensionUtils.LocalDateFormatEnum
.YYYY_MM_DD_HH_MM_SS.getDateFormatter());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, dateTime.getYear());
calendar.set(Calendar.MONTH, dateTime.getMonthValue() - 1);
calendar.set(Calendar.DATE, dateTime.getDayOfMonth());
calendar.set(Calendar.HOUR_OF_DAY, dateTime.getHour());
calendar.set(Calendar.MINUTE, dateTime.getMinute());
calendar.set(Calendar.SECOND, dateTime.getSecond());
return calendar;
}
}
return super.deserialize(p, ctxt);
}
}
static class CustomDateDeSerializer extends DateDeserializers.DateDeserializer {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (p != null) {
String calendatStr = p.getText();
if (StringUtils.isNotBlank(calendatStr) && !StringUtils.contains(calendatStr, 'T') &&
calendatStr.length() == 19) {
LocalDateTime dateTime = LocalDateTime.parse(calendatStr, ExtensionUtils.LocalDateFormatEnum
.YYYY_MM_DD_HH_MM_SS.getDateFormatter());
return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
}
}
return super.deserialize(p, ctxt);
}
}
}
/**
* 获取JSON序列化
*
* @return
*/
public static JacksonUtils getInstance() {
return Singleton.INSTANCE;
}
/**
* 序列化
*
* @param obj
* @return throw IOException
*/
public String serialize(Object obj) {
if (obj == null) {
return StringUtils.EMPTY;
}
String jsonStr = StringUtils.EMPTY;
try {
jsonStr = Singleton.MAPPER.writeValueAsString(obj);
} catch (Exception e) {
Throwables.propagate(e);
}
return jsonStr;
}
/**
* 反序列化
*/
public
T deserialize(String s, Class clazz) {
if (StringUtils.isBlank(s)) {
return null;
}
T result = null;
try {
result = Singleton.MAPPER.readValue(s, clazz);
} catch (Exception e) {
Throwables.propagate(e);
}
return result;
}
}