SPRINGMVC format problem handling for returning Java 8 time JSON data

Source: Internet
Author: User

Annotations are sometimes used when returning JSON-formatted response in spring MVC, @ResponseBody but it can be cumbersome when dealing with time, and the httpmessageconverter that we typically use is MappingJackson2HttpMessageConverter that the time format it returns by default is this:

1"StartDate" : {2"Year": 2010,3"Month": "January",4"DayOfMonth": 1,5"DayOfWeek": "FRIDAY",6"DayOfYear": 1,7"Monthvalue": 1,8"Hour": 2,9"Minute": 2,Ten"Second": 0, One"Nano": 0, A"Chronology" : { -"id": "ISO", -"CalendarType": "iso8601" the     } -}

But in general we will not return this to the front-end use, for Localdate want to return the format is 2016-11-26,而LocalDateTime想要返回的格式是2016-11-26  21:04:34 such data. Through project research and access to relevant information, here are two ways to achieve this in your personal research.

Workaround One:

For MAVEN projects, introduce the following jar package in the POM:

1 <dependency>2      <groupId>com.fasterxml.jackson.datatype</groupId>3       <artifactId>jackson-datatype-jsr310</artifactId>4      <version>2.8.5</ Version>5 </dependency>

Then add an annotation to the Get function of the Pojo field that you want to JSON @JsonSerializer , as follows

1 ImportCom.fasterxml.jackson.annotation.JsonFormat;2 3@JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "YYYY-MM-DD"))4  PublicLocalDateTime Getbirthday () {5         return  This. Logintime;6     }7 8@JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "Yyyy-mm-dd HH:mm:ss")9  PublicLocalDateTime Getlastlogintime () {Ten         return  This. Logintime; One}

The advantage of this approach is that you can set different display modes for specific domain types, but the pros are also a disadvantage because you want to write annotations like above on each pojo, and you need to introduce additional jsr310 jar packages.

Workaround Two:

Custom Localdate and LocalDateTime serialization classes, and register to object mapper

1 /**2 * JSON processing tool class3  * 4  * 5  */6 @Component7  Public classJsonutil {8 9     Private Static FinalObjectmapper Mapper;Ten  One      Publicobjectmapper Getmapper () { A         returnmapper; -     } -  the     Static { -  -Mapper =NewObjectmapper (); -  +Simplemodule module =Newsimplemodule (); -Module.addserializer (localdate.class,NewLocaldateserializer ()); +Module.addserializer (localtime.class,NewLocaltimeserializer ()); AModule.addserializer (LocalDateTime.class,NewLocaldatetimeserializer ()); at mapper.registermodule (module); -     } -  -      Public StaticString ToJson (Object obj) { -         Try { -             returnmapper.writevalueasstring (obj); in}Catch(Exception e) { -             Throw NewRuntimeException ("Convert JSON character failed!")); to         } +     } -  the      Public<T> T Toobject (String json, class<t>clazz) { *         Try { $             returnMapper.readvalue (JSON, clazz);Panax Notoginseng}Catch(IOException e) { -             Throw NewRuntimeException ("Failed to convert JSON character to Object!")); the         } +     } A } the  + classLocaldateserializerextendsJsonserializer<localdate> { -  $     Private Static FinalDateTimeFormatter dateformatter = Datetimeformatter.ofpattern ("Yyyy-mm-dd"); $  - @Override -      Public voidSerialize (localdate value, Jsongenerator Jgen, serializerprovider provider) the             throwsIOException, jsonprocessingexception { - jgen.writestring (Dateformatter.format (value));Wuyi     } the } -  Wu classLocaldatetimeserializerextendsJsonserializer<localdatetime> { -  About     Private Static FinalDateTimeFormatter DateTimeFormatter = Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss"); $  - @Override -      Public voidSerialize (LocalDateTime value, Jsongenerator Jgen, serializerprovider provider) -             throwsIOException, jsonprocessingexception { A jgen.writestring (Datetimeformatter.format (value)); +     } the  - } $  the classLocaltimeserializerextendsJsonserializer<localtime> { the  the     Private Static FinalDateTimeFormatter Timeformatter = Datetimeformatter.ofpattern ("HH:mm:ss"); the  - @Override in      Public voidSerialize (localtime value, Jsongenerator Jgen, serializerprovider provider) the             throwsIOException, jsonprocessingexception { the jgen.writestring (Timeformatter.format (value)); About  the     } the  the}
View Code

Then in the SPRINGMVC configuration file, change <mvc:annotation-driven/> to the following configuration, configure a new JSON converter, Set its Objectmapper object to the Objectmapper object in Jsonutil, which has a higher precedence than the spring built-in JSON converter, so the JSON-related conversion will take precedence over it.

1<mvc:annotation-driven>2<mvc:message-converters>3<Bean4                 class= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >5<property name= "Objectmapper" value= "#{jsonutil.mapper}"/>6<property name= "Supportedmediatypes" >7<list>8<value>application/json;charset=UTF-8</value>9</list>Ten</property> One</bean> A</mvc:message-converters> -</mvc:annotation-driven>
View Code

Then several date and time types in the JAVA8 can be displayed in a normal and friendly style. The advantage is the global unified management date and time, and other types, the disadvantage of a domain in the Pojo to do special processing.

SPRINGMVC format problem handling for returning Java 8 time JSON data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.