SPINGMVC returns the JSON data date formatting method

Source: Internet
Author: User

The first type:

JSON uses this dependency.

<!--JSON Lib development package and its dependency package--
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>

When SPRINGMVC returns JSON data, the default Date field displays a long type of timestamp

If you want to return a formatted date such as: YYYY-MM-DD This format needs to appear

Here's how:

Write a single processing class inheritance Jsonserializer

Code
12345678910111213141516171819 import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.SerializerProvider;public class CustomDateSerializer extends JsonSerializer<Date> {     @Override    public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException,            JsonProcessingException {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        jsonGenerator.writeString(sdf.format(value));    }}

Add a @jsonserialize annotation to an attribute field on an entity class

Code
12 @JsonSerialize(using = CustomDateSerializer.class) privateDate createTime;

The second type:

This package supports the case

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

SPRINGMVC date format for returning JSON when using @responsebody

Prerequisites to understand: @ResponseBody The core class that returns the JSON string is Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter, which uses the open-source third-party class library of Jackson. The main is the following two jar packages: Jackson-core-asl-1.6.4.jar;jackson-mapper-asl-1.6.4.jar.

Problem: Returns the date format of the JSON string when using @responsebody. The Date Type property returns a long timestamp by default, and how can I return a custom date format?

Solution: There are two ways to achieve this,

1, local modification (online more, but not recommended);

Inherit Jackson's abstract class: Jsonserializer<t>, and then add annotations @jsonserialize on JavaBean's property getter () to implement.

The code is as follows:

Java code
  1. Import java.io.IOException;
  2. Import Java.text.SimpleDateFormat;
  3. Import Java.util.Date;
  4. Import Org.codehaus.jackson.JsonGenerator;
  5. Import org.codehaus.jackson.JsonProcessingException;
  6. Import Org.codehaus.jackson.map.JsonSerializer;
  7. Import Org.codehaus.jackson.map.SerializerProvider;
  8. /**
  9. * @description Custom Returns the format of the date in the JSON data grid processing
  10. * @author Aokunsang
  11. * @date 2013-5-28
  12. */
  13. Public class Customdateserializer extends jsonserializer<date> {
  14. @Override
  15. public void Serialize (Date value,
  16. Jsongenerator Jsongenerator,
  17. Serializerprovider provider)
  18. throws IOException, jsonprocessingexception {
  19. SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
  20. Jsongenerator.writestring (Sdf.format (value));
  21. }
  22. }

How to use:

Java code
    1. @JsonSerialize (using = Customdateserializer. Class)
    2. Public Date getcreatedate () {
    3. return createdate;
    4. }

2. Global modification (highly recommended):

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.

The code is as follows:

Java code
  1. Import java.io.IOException;
  2. Import Java.text.SimpleDateFormat;
  3. Import Java.util.Date;
  4. Import Org.codehaus.jackson.JsonGenerator;
  5. Import org.codehaus.jackson.JsonProcessingException;
  6. Import Org.codehaus.jackson.map.JsonSerializer;
  7. Import Org.codehaus.jackson.map.ObjectMapper;
  8. Import Org.codehaus.jackson.map.SerializerProvider;
  9. Import Org.codehaus.jackson.map.ser.CustomSerializerFactory;
  10. /**
  11. * @description Resolve Date type return JSON format to custom format
  12. * @author Aokunsang
  13. * @date 2013-5-28
  14. */
  15. Public class Customobjectmapper extends Objectmapper {
  16. Public Customobjectmapper () {
  17. Customserializerfactory factory = new Customserializerfactory ();
  18. Factory.addgenericmapping (Date. Class, new Jsonserializer<date> () {
  19. @Override
  20. public void Serialize (Date value,
  21. Jsongenerator Jsongenerator,
  22. Serializerprovider provider)
  23. throws IOException, jsonprocessingexception {
  24. SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
  25. Jsongenerator.writestring (Sdf.format (value));
  26. }
  27. });
  28. this.setserializerfactory (Factory);
  29. }
  30. }

Configuration in Spring-servlet.xml:

Java code
  1. <mvc:annotation-driven>
  2. <mvc:message-converters>
  3. <bean class="Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
  4. <property name="Objectmapper" ref="Customobjectmapper" ></property>
  5. </bean>
  6. </mvc:message-converters>
  7. </mvc:annotation-driven>
  8. <bean id="Customobjectmapper" class="Com.pmc.dwa.common.custom.CustomObjectMapper" ></bean >

Second, @DatetimeFormat the use of attention

1, the use of @datetimeformat is very simple, it should be noted here: use to introduce a class library Joda-time-1.3.jar, otherwise you will not be able to access the corresponding path (400 error).

PS: This annotation can work on Method,field and parameter levels.

Reference for use: http://www.captaindebug.com/2011/08/using-spring-3-datetimeformat.html#.UaR3mWWZk0k

2. Because SPRINGMVC does not provide a default date converter, the previous page passes over how the date string is converted to a date type, and can be done using the @datetimeformat annotation if no global date converter or data binding is provided.

SPINGMVC returns the JSON data date formatting method

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.