Spring MVC JSON returns JSON for date format issues

Source: Internet
Author: User

(i) Output JSON data

JSON output can be done using JACKSON-MAPPER-ASL in springmvc, with several configurations:

1. Using Mvc:annotation-driven2. Adding JACKSON-MAPPER-ASL to Dependency management

<dependency>        <groupId>org.codehaus.jackson</groupId>        <artifactId> Jackson-mapper-asl</artifactid>        <version>${jackson.version}</version></dependency>

3. Using annotations @responsebody

Mvc:annotation-driven The JSON converter is loaded by default, we can use annotation @responsebody to return JSON data when we add the above dependency package, such as

@RequestMapping ("json") @ResponseBody public list<user> userlist (modelmap Modelmap) {          New userexample ();         Example.createcriteria (). andusernameisnotnull ();         List<User> users = usermapper.selectbyexample (example);          return users;}

(ii) format the date format of the JSON output

Although JSON is output, JSON has a long value for the date type, like when the page is taken out as a foreign date format, we need to add a format conversion to convert the date format to the desired format: YYYY-MM-DD.

1. Using @jsonformat (pattern= "yyyy-mm-dd HH:mm:ss", timezone = "gmt+8")

Add @jsonformat (pattern= "yyyy-mm-dd HH:mm:ss", timezone = "gmt+8") above the Getter method of the entity class to format the date of the Json.

The first time I try to always fail, and then add a complete dependency package after success, you need to add several dependencies as Follows:

<!--json data--         <dependency>             <groupId>org.codehaus.jackson</groupId>             < artifactid>jackson-mapper-asl</artifactid>             <version>${jackson.version}</version>         </dependency>         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-core</artifactId>             <version>${jackson.core.version}</version>         </dependency>         <dependency>             <groupid>com.fasterxml.jackson.core</groupid >             <artifactId>jackson-databind</artifactId>             <version>${jackson.core.version} </version>         </dependency>  <properties>         <jackson.version>1.9.13</ Jackson.version>         <jackson.core.version>2.4.2</jackson.core.version></properties>

The advantage is simple and convenient, and the disadvantage is that it needs to be added on the getter method for each desired Property. Macro look more cumbersome, but the actual development of a line of code, the only bad thing is that MyBatis automatically generated entity class will be Overwritten.

2. Inheriting objectmapper to implement the return JSON string

Reference: http://aokunsang.iteye.com/blog/1878985

Although the above method is simple and convenient, but the disadvantage is also obvious, the automatic generation of code will overwrite the entity class, and each date attribute to be added manually, the actual date attribute is a universal Necessity. therefore, the large can be processed globally, in a uniform format. In this case, the date and timestamp in the database will be converted to the Date object by Mybatis. The format specification for birthdays to days and minutes to seconds allows the display layer to be processed. Unified into yyyy-mm-dd HH:mm:ss

The Mappingjacksonhttpmessageconverter is primarily implemented by Objectmapper to return a JSON string. Here we inherit the class, registering a jsonserializer<t>. The custom objectmapper is then injected into the configuration File.

2.1 Writing Subclass inheritance Objectmapper

 packagecom.demo.common.util.converter;Importorg.codehaus.jackson.JsonGenerator;Importorg.codehaus.jackson.JsonProcessingException;Importorg.codehaus.jackson.map.JsonSerializer;Importorg.codehaus.jackson.map.ObjectMapper;Importorg.codehaus.jackson.map.SerializerProvider;Importorg.codehaus.jackson.map.ser.CustomSerializerFactory;Importjava.io.IOException;Importjava.text.SimpleDateFormat;Importjava.util.Date; /*** Fix Date type returns JSON format for custom format * Created by Administrator on 2016/2/14. */  public classCustomjsondateconverterextendsObjectmapper { publiccustomjsondateconverter () {customserializerfactory Factory=Newcustomserializerfactory (); Factory.addgenericmapping (Date.class,NewJsonserializer<date>() {@Override public voidSerialize (Date value, jsongenerator jsongenerator, Serializerprovider Provider)throwsIOException {simpledateformat SDF=NewSimpleDateFormat ("YYYY-MM-DD HH:mm:ss");             Jsongenerator.writestring (sdf.format (value));         }         });  this. Setserializerfactory (factory); } }

2.2 Configuring Spring Files

<mvc:annotation-driven>         <mvc:message-converters>             class= " Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter ">                 <property name=" Objectmapper "ref=" customobjectmapper "></property>             </bean>         class=" Com.demo.common.util.converter.CustomJsonDateConverter "></bean>

2.3 Display Layer self-determining date type length

This configuration cannot be used in conjunction with the previous @jsonformat. Date and datetime, as well as timestamp, are all formatted as a result of a globally uniform format, and if date fields such as birthdays need to be streamlined, they can only be cropped at the display Layer.

3. Use the built-in Date formatting tool

The same is true for the global setting of the date format of the JSON response, but this method can coexist with @jsonformat, which means that a format can be set globally, with annotation settings for specific requirements.

3.1 Configuring Spring Files

 <mvc:annotation-driven> <!--processing responsebody inside date type--<mvc:message-converters> <bean class  = " Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter "> <property name=" objec Tmapper "> <bean class  =" com.fasterxml.jackson.databind.Obje Ctmapper "> <property name=" dateformat "> <bean class  = "java.text.SimpleDateFormat" > <constructor-arg type= "java.lang.String                      "value=" yyyy-mm-dd HH:mm:ss "/> </bean> </property> </bean> </property> </bean> </mvc:message -converters> </mvc:annotation-driven> 

3.2 Configuring a specific date
@JsonFormat (pattern= "yyyy-mm-dd", timezone = "gmt+8") public    Date Getbirth () {        return birth;    }

Spring MVC JSON returns JSON for date format issues

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.