1. 程式人生 > 實用技巧 >springboot LocalDateTime,Json資料序列化

springboot LocalDateTime,Json資料序列化

1. 邏輯說明

spring程式啟動後會自動建立物件轉換工具org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
根據能找到的java解析json包來依次處理

jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("javax.json.bind.Jsonb", classLoader);

建立AbstractJackson2HttpMessageConverter物件
不走bean的建立過程, 所以spring.jackson.* 配置和注入ObjectMapper的方式都是沒有辦法調整解析結果的
有效的方式有兩種

1). WebMvcConfigurationSupport中修改

//啟動的時候進入ObjectMapper 構造斷點,系統自動建立了
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.extendMessageConverters(converters);
    for (HttpMessageConverter<?> converter : converters){
        if (converter instanceof AbstractJackson2HttpMessageConverter){
           AbstractJackson2HttpMessageConverter jackson2HttpMessageConverter = (AbstractJackson2HttpMessageConverter)converter;
            jackson2HttpMessageConverter.getObjectMapper().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            jackson2HttpMessageConverter.getObjectMapper().setLocale(Locale.CHINA);
            jackson2HttpMessageConverter.getObjectMapper().setTimeZone(TimeZone.getTimeZone("GMT+:08:00"));
            jackson2HttpMessageConverter.getObjectMapper().setDateFormat(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
            //jackson2HttpMessageConverter.getObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))            
        }
    }
}

2). 使用 @DateTimeFormat 和 @JsonFormat 註解,@JsonFormat(timezone = "GMT+8", pattern = "yyyyMMddHHmmss")

參考com.fasterxml.jackson.datatype.jsr310.ser中的邏輯判斷

先用 this._formatter ,不存在使用_defaultFormatter

 public void serialize(LocalDateTime value, JsonGenerator g, SerializerProvider provider) throws IOException {
        if (this.useTimestamp(provider)) {
            g.writeStartArray();
            this._serializeAsArrayContents(value, g, provider);
            g.writeEndArray();
        } else {
            DateTimeFormatter dtf = this._formatter;
            if (dtf == null) {
                dtf = this._defaultFormatter();
            }
            g.writeString(value.format(dtf));
        }
    }
 protected DateTimeFormatter _defaultFormatter() {
       return DateTimeFormatter.ISO_LOCAL_DATE_TIME;
  }