"Giant Pit" SPRINGMVC output JSON format data in several ways!

Source: Internet
Author: User
Tags dateformat string format

Recently, the company project needs to publish some data services, from design to implementation two days to finish, the hearts of joy.  As a result of the imminent deployment, suddenly found ..... The data output format for the date type in the JSON data for the service output is either a timestamp or {"Date": 1, "Day": +, "hours": 5, "month": minutes, "seconds": "Time" : 1498484302259, "Timezoneoffset": -480, "Year": 117} This format. Sister's, I'm dying! Thanks to Baidu, thank you for the urgency of my predecessors, working at home for three hours summed up several methods of date data format conversion;

Premise: Need rack Package Jackson-annotations-2.7.4.jar, Jackson-core-2.7.4.jar, Jackson-databind-2.7.4.jar

The first: Directly on the config file configured in Springmvc, the annotation configuration is changed to:

<mvc:annotation-driven><mvc:message-converters><bean class= " Org.springframework.http.converter.StringHttpMessageConverter "><property name=" Supportedmediatypes "> <list><value>application/json;charset=utf-8</value></list></property></bean ><!--Json Conversion configuration--><bean class= " Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter "><property name=" Objectmapper                                             "> <bean class=" Com.fasterxml.jackson.databind.ObjectMapper "> <property name= "DateFormat" > <bea n class= "Java.text.SimpleDateFormat" > <constructor-arg type= "java. Lang.                                             String "value=" Yyyy-mm-dd HH:mm:ss "/> </bean>                 </property>                       </bean> </property> <property name= "Supportedmedia Types "><list><value>text/plain;charset=utf-8</value> <value>tex                                T/html;charset=utf-8</value> <value>text/json;charset=utf-8</value> <value>application/json;charset=utf-8</value></list></property></bean ></mvc:message-converters></mvc:annotation-driven>

This method is simple. It's too easy. No additional configuration is required and is globally valid.

Second for data that needs to be converted independently (partial conversion)

The above configuration can be used without the need to customize the implementation of JSON serialized date data

//Not much content, mainly in order to specify the mode of conversion
Importjava.io.IOException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportCom.fasterxml.jackson.core.JsonGenerator;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.JsonSerializer;ImportCom.fasterxml.jackson.databind.SerializerProvider; Public classCustomdateserializerextendsJsonserializer<date>{@Override Public voidSerialize (Date arg0, Jsongenerator arg1, Serializerprovider arg2)throwsIOException, jsonprocessingexception {simpledateformat SDF=NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); Conversion Format arg1.writestring (Sdf.format (arg0)); Write the converted value}}

All right, it's all written. Now we just need to add the annotations @JsonSerialize on the date field that needs to be converted:

@JsonSerialize (using = Customdateserializer.  Class)  //Use annotation @JsonFormat (pattern= "Yyyy/mm/dd HH:mm:ss", timezone = "gmt+8") can also    be private Date time2;

There's no more action.

The third: Also for the global transformation of the way, need a tool class (careful observation and the second many similar places)

/*+--------------------------------------------------------------------------|   Mblog [#RELEASE_VERSION #]|   ========================================| Copyright (c), Mtons.   All Rights reserved| http://www.mtons.com|+---------------------------------------------------------------------------*/ PackageCom.dm.restWeb.config;Importjava.io.IOException;Importjava.lang.reflect.AnnotatedElement;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportOrg.springframework.format.annotation.DateTimeFormat;Importorg.springframework.stereotype.Component;ImportCom.fasterxml.jackson.core.JsonGenerator;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.JsonSerializer;ImportCom.fasterxml.jackson.databind.ObjectMapper;ImportCom.fasterxml.jackson.databind.SerializerProvider;Importcom.fasterxml.jackson.databind.introspect.Annotated;ImportCom.fasterxml.jackson.databind.introspect.AnnotatedMethod;ImportCom.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;/** * @authorLANGHSU **/@Component Public classJsonutils {Private Static FinalString Default_date_format = "Yyyy-mm-dd"; Private Static FinalObjectmapper Mapper;  Publicobjectmapper Getmapper () {returnmapper; }    Static{SimpleDateFormat DateFormat=NewSimpleDateFormat (Default_date_format); Mapper=NewObjectmapper ();        Mapper.setdateformat (DateFormat); Mapper.setannotationintrospector (NewJacksonannotationintrospector () {Private Static Final LongSerialversionuid = -5854941510519564900l; @Override PublicObject Findserializer (annotated a) {if(AinstanceofAnnotatedmethod) {annotatedelement m=a.getannotated (); DateTimeFormat an= M.getannotation (DateTimeFormat.class); if(An! =NULL) {                        if(!default_date_format.equals (An.pattern ())) {                            return NewJsondateserializer (An.pattern ()); }                    }                }                return Super. Findserializer (a);    }        }); }     Public StaticString ToJson (Object obj) {Try {            returnmapper.writevalueasstring (obj); } Catch(Exception e) {Throw NewRuntimeException ("Convert JSON character failed!")); }    }     Public<T> T Toobject (String json, class<t>clazz) {        Try {            returnMapper.readvalue (JSON, clazz); } Catch(IOException e) {Throw NewRuntimeException ("Failed to convert JSON character to Object!")); }    }     Public Static classJsondateserializerextendsJsonserializer<date> {        PrivateSimpleDateFormat DateFormat;  Publicjsondateserializer (String format) {DateFormat=NewSimpleDateFormat (format); } @Override Public voidSerialize (date date, Jsongenerator Gen, Serializerprovider provider)throwsIOException, jsonprocessingexception {String value=Dateformat.format (date);        Gen.writestring (value); }    }}

In fact, it is a static method to achieve the acquisition of Objectmapper object;

You also need to write the configuration in the Springmvc configuration file:

<mvc:annotation-driven> <mvc:message-converters> <beanclass= "Org.springframework.http.converter.StringHttpMessageConverter" > <property name= "supportedmediatypes                    "> <list> <value>application/json;charset=UTF-8</value>            </list> </property> </bean> <!--Json-- <beanclass= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name= "objec Tmapper "value=" #{jsonutils.mapper} "/> <!--and the first method configuration mode--&LT;PR Operty name= "Supportedmediatypes" > <list> <value>text/plain;chars Et=utf-8</value> <value>text/html;charset=utf-8</value> &L T;value>text/json;charset=utf-8</value> <value>application/json;charset=utf-8</va lue> </list> </property> </bean> </mvc:message -converters> </mvc:annotation-driven>

You will find that the third method is similar to the first method, but the third method supports the use of @JsonFormat annotations to achieve a specific output of the specified date format.

So from the code implementation it seems that the third way features the most comprehensive, the first way configuration is the simplest, the second configuration method is not recommended.

  

"Giant Pit" SPRINGMVC output JSON format data in several ways!

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.