搜尋
首頁Javajava教程解決SpringMVC 傳回Java8 時間JSON資料的格式化問題處理的詳解

本篇文章主要介紹了解決SpringMVC 回傳Java8 時間JSON資料的格式化問題處理,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

有時在Spring MVC中返回JSON格式的response的時候會使用@ResponseBody註解,不過在處理java8中時間的時候會很麻煩,一般我們使用的HTTPMessageConverter是MappingJackson2HttpMessageConverter,它預設回傳的時間格式是這種:

"startDate" : {
  "year" : 2010,
  "month" : "JANUARY",
  "dayOfMonth" : 1,
  "dayOfWeek" : "FRIDAY",
  "dayOfYear" : 1,
  "monthValue" : 1,
  "hour" : 2,
  "minute" : 2,
  "second" : 0,
  "nano" : 0,
  "chronology" : {
   "id" : "ISO",
   "calendarType" : "iso8601"
  }
 }

##但是我們不會回傳這種給前端使用,針對LocalDate想要傳回的格式是2016-11-26,而LocalDateTime想要回傳的格式是2016-11-26 21:04:34這樣的資料。透過專案研究並查閱相關資料,這裡介紹下個人研究中實現的兩種方式。

解決方法一:

若是maven項目,在pom中引入下面的jar套件:

<dependency>
   <groupId>com.fasterxml.jackson.datatype</groupId>
   <artifactId>jackson-datatype-jsr310</artifactId>
   <version>2.8.5</version>
 </dependency>

然後在你想要JSON化的POJO欄位的get函數上加上一個@JsonSerializer註解,如下


import com.fasterxml.jackson.annotation.JsonFormat;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
public LocalDateTime getBirthday() {
    return this.loginTime;
  }

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime getLastLoginTime() {
    return this.loginTime;
  }

這種方式的優點是可以針對特定域類型設定不同顯示方式,然而優點也是缺點,因為每個日期屬性都要手動添加,實際中日期屬性又是普遍必備,並且需要額外引入jsr310的jar包。

解決方法二:

繼承ObjectMapper來實作傳回json字串。 MappingJackson2HttpMessageConverter主要透過ObjectMapper來實作傳回json字串。這裡我們寫一個JsonUtil類,取得ObjectMapper以針對java8新的日期時間API,註冊對應的JsonSerializer

/**
 * json处理工具类
 * 
 * 
 */
@Component
public class JsonUtil {

  private static final ObjectMapper mapper;

  public ObjectMapper getMapper() {
    return mapper;
  }

  static {

    mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    module.addSerializer(LocalDate.class, new LocalDateSerializer());
    module.addSerializer(LocalTime.class, new LocalTimeSerializer());
    module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
    mapper.registerModule(module);
  }

  public static String toJson(Object obj) {
    try {
      return mapper.writeValueAsString(obj);
    } catch (Exception e) {
      throw new RuntimeException("转换json字符失败!");
    }
  }

  public <T> T toObject(String json, Class<T> clazz) {
    try {
      return mapper.readValue(json, clazz);
    } catch (IOException e) {
      throw new RuntimeException("将json字符转换为对象时失败!");
    }
  }
}

class LocalDateSerializer extends JsonSerializer<LocalDate> {

  private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

  @Override
  public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {
    jgen.writeString(dateFormatter.format(value));
  }
}

class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

  private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  @Override
  public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {
    jgen.writeString(dateTimeFormatter.format(value));
  }

}

class LocalTimeSerializer extends JsonSerializer<LocalTime> {

  private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

  @Override
  public void serialize(LocalTime value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {
    jgen.writeString(timeFormatter.format(value));

  }

}

然後在springmvc的設定檔中,再將改為以下配置,設定一個新的json轉換器,將它的ObjectMapper物件設定為JsonUtil中的objectMapper對象,此轉換器比spring內建的json轉換器優先權更高,所以與json有關的轉換,spring會優先使用它。


<mvc:annotation-driven>
    <mvc:message-converters>
      <bean
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="objectMapper" value="#{jsonUtil.mapper}" />
        <property name="supportedMediaTypes">
          <list>
            <value>application/json;charset=UTF-8</value>
          </list>
        </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

然後java8中的幾個日期和時間類型就可以正常友善的顯示了。優點是全域統一管理日期和時間等類型,缺點對pojo中的某個域做特殊處理。


 以上就是解決SpringMVC 返回Java8 時間JSON資料的格式化問題處理的詳解的內容,更多相關內容請關注PHP中文網(www.php.cn)!



#

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JVM性能與其他語言JVM性能與其他語言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台獨立性:使用示例Java平台獨立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架構:深入研究Java虛擬機JVM架構:深入研究Java虛擬機May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM與操作系統有關嗎?JVM:JVM與操作系統有關嗎?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:寫一次,在任何地方跑步(WORA) - 深入了解平台獨立性Java:寫一次,在任何地方跑步(WORA) - 深入了解平台獨立性May 14, 2025 am 12:05 AM

Java實現“一次編寫,到處運行”通過編譯成字節碼並在Java虛擬機(JVM)上運行。 1)編寫Java代碼並編譯成字節碼。 2)字節碼在任何安裝了JVM的平台上運行。 3)使用Java原生接口(JNI)處理平台特定功能。儘管存在挑戰,如JVM一致性和平台特定庫的使用,但WORA大大提高了開發效率和部署靈活性。

Java平台獨立性:與不同的操作系統的兼容性Java平台獨立性:與不同的操作系統的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什麼功能使Java仍然強大什麼功能使Java仍然強大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

頂級Java功能:開發人員的綜合指南頂級Java功能:開發人員的綜合指南May 13, 2025 am 12:04 AM

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境