本篇文章主要介紹了解決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的設定檔中,再將
<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中的某個域做特殊處理。
#

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

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

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

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

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

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

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

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

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

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

SublimeText3漢化版
中文版,非常好用

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境