Use Jackson in SPRINGMVC and format time

Source: Internet
Author: User
Tags time zones

In Spring MVC 3, the simplest way to implement the rest-style JSON service is to use @ResponseBody annotations. The annotation automatically serializes the returned object to JSON.

Take a look at one of the simplest examples. This example first uses spring 3.0.5 + Jackson1.7.1. Jackson is the JSON serialized/deserialized third-party library used by spring.

The main contents of Pom.xml are as follows

    <!--Spring Framework Dependencies--    <dependency> <groupId>Org.springframework</groupId> <artifactId>Spring-context</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>Org.springframework</groupId> <artifactId>Spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>Org.springframework</groupId> <artifactid>spring-orm</artifactid>  <version>3.0.5.release</ Version> </dependency> <!-- Jackson JSON--> <dependency>  <groupid>org.codehaus.jackson</groupid> <artifactid>jackson-mapper-asl</artifactid>  <version>1.7.1</version>< Span class= "PLN" > </DEPENDENCY>          

A POJO object testparams is defined and returned by the controller's Dotestquery method.

Public  Class Testparams { Private DateFormattime; Private DateOrigintime; Private IntI; Public DateGetformattime() { ReturnFormattime; } Public DateGetorigintime() { ReturnOrigintime; } Public IntGeti() { ReturnI; } Public voidSetformattime(DateFormattime) { This.Formattime=Formattime; } Public voidSetorigintime(DateOrigintime) { This.Origintime=Origintime; } Public voidSeti(IntI) { This.I=I; }}@ResponseBody@RequestMapping(Value="/test",Method=Requestmethod.GET)Public ObjectDotestquery() { Testparams Params = New Testparams(); Params = new testparams (); Span class= "PLN" > date now =new date (); params. Setformattimenowparams. Setorigintimenowreturn params;                /span>                

Request sample URL, browser return

{    "formatTime": 1412509897631, "originTime": 1412509897631, "i": 0}

And the type of message content returned is also duly completed:Content-Type:application/json;charset=UTF-8

It's just that time looks awkward.

By default, Jackson is Java.util.Date serialized epoch timestamp , and the time zone uses GMT standard Time, not the local time zone.

"Because it's the most effective and accurate."

Why does Dates get written as numbers?

Default Serializer for Java.util.Date (and related, such as Java.util.Calendar) serialize them using the most efficient AC Curate representation, so-called epoch timestamp (number of milliseconds since January 1st, 1970, UTC). Assumption is the if user does not care, we should use efficient and accurate representation to get job Bdone

If you've developed a Web site across continents that spans time zones, you'll know that the above is a practice.

So what do I do when I want a well-readable time format?

In the jackson1.x era, you can expand to JsonSerializer implement a format time JsonDateSerializer , and reference this class in annotations

@JsonSerialize(using=JsonDateSerializer.class)public Date getDate() { return date;}

See "How to Serialize Java.util.Date with Jackson JSON processor/spring 3.0" for details.

This method makes people not love, weak and troublesome feeling.

Further query, found that there is an annotation @JsonFormat can easily format the time field.

But this note looked at the next only in Jackson2. So I fell into the spring version and Jackson2 of the myth, a toss.

If you don't want to use @JsonFormat annotations, jackson-mapper-asl you can still use the 1.x version to match the Spring 3.x series.

If you want to use @JsonFormat annotations, you need to upgrade spring to 3.1.2.
And to replace Jackson's jar package with the 2.x series (compared to the 1.x series, the package name is changed).

The upgraded pom.xml are as follows:

    <!--Spring Framework Dependencies--    <dependency> <groupId>Org.springframework</groupId> <artifactId>Spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>Org.springframework</groupId> <artifactId>Spring-context-support</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>Org.springframework<groupId> <artifactId>Spring-webmvc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>Org.springframework</groupId> <artifactId>Spring-orm</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>Com.fasterxml.jackson.core</groupId> <artifactId>Jackson-core</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>Com.fasterxml.jackson.core</groupid> <artifactid></artifactid> <version>< Span class= "PLN" >2.2.3</version> </dependency>  <dependency> <groupid>com.fasterxml.jackson.core</groupid>  <artifactid>jackson-databind</artifactid> span class= "tag" ><version>2.2.3</version> span class= "tag" ></DEPENDENCY>            

At this time, you can happily add annotations to the Testparams.

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date formatTime;

Visit the test URL again to return the JSON object as follows

{    "formatTime": "2014-10-05 20:20:15", "originTime": 1412511615062, "i": 0}

Reference links

    • Jackson faq:date Handling

    • How to Serialize Java.util.Date with Jackson JSON processor/spring 3.0

    • Backport "Use of Jackson 2.0 for Jackson based JSON processing such as Mappingjacksonjsonview"

    • Notes on upgrading Jackson from 1.9 to 2.0

Use Jackson in SPRINGMVC and format time

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.