Receive and respond to JSON-formatted data with SPRINGMVC @requestbody and @responsebody

Source: Internet
Author: User

1.controller

@Controller @requestmapping ("/rest/v1")  Public class Welcomecontroller {@RequestMapping (value= "/date/json/next",            method=requestmethod.post, Consumes= "Application/json"            , produces= "Application/json")    @ResponseBody      Public datetime getnextdatejson (@RequestBody datetime date)    {        date.getnowdate (). SetTime (                date.getnowdate (). GetTime ());         return date;    }   }

2. Request the parameter class and return the Class DateTime (DateTime was originally used to test the return time format, where the lazy request and return are in the same class)

 PackageCom.cici.example.view.domain;ImportJava.sql.Timestamp;ImportCom.cici.utils.TimestampSerializer;Importcom.fasterxml.jackson.databind.annotation.JsonSerialize; Public classDateTime {String name; @JsonSerialize (using=timestampserializer.class) Timestamp nowdate;  PublicTimestamp getnowdate () {returnnowdate; }     Public voidsetnowdate (Timestamp nowdate) { This. nowdate =nowdate; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }        }

Launch Tomcat and then use Chrome's postman or Firefox httprequester to send the JSON parameter's post request with the following parameters

{"nowdate": "2016-7-8t16:33:15.687","name": "CC"}

If you return 415 Unsupport media type at this time, there are two possible reasons (configuration is configured in the MAVEN build SPRINGMVC project)

1) messageconverters not configured to support Application/json type

2) Pom.xml did not configure Jackson's dependency (Fasterxml or Haus pack)

At this time the nowdate timestamp type SPRINGMVC is unresolved and the request returns

Because I use the Jackson Bag is fasterxml, so there are two ways to solve (if using Haus may have three kinds of)

1) Add a sentence @datetimeformat (pattern = "Yyyy-mm-dd ' T ' HH:mm:ss) to the Nowdate attribute of the Datetime.java class. Sssz "), but this method needs to be configured once for each timestamp type of each class, not recommended

2) Customize a converter, this way only need to configure once, recommend this way

Dateconverter.java

 Packagecom.cici.utils;ImportJava.sql.Timestamp;ImportOrg.springframework.core.convert.converter.Converter; Public classDateConverterImplementsConverter<string,timestamp>{@Override PublicTimestamp Convert (String date) {if(NULL!=date) {            returntimestamp.valueof (date); }        return NULL; }}

Then configure the Dispatcher-servlet.xml in the

<!--This is to add the conversion-service= "Conversionservice" to the original Annotation-driven. -<Mvc:annotation-drivenConversion-service= "Conversionservice"/><BeanID= "Conversionservice"class= "Org.springframework.format.support.FormattingConversionServiceFactoryBean">        < Propertyname= "Converters">            <List>                <Beanclass= "Com.cici.utils.DateConverter" >                </Bean>            </List>        </ Property>    </Bean>

But the goose. Nowdate in response returns a long timestamp, not a specific time, you can write a jsonserializer for properties of timestamp type (this method requires that each property be configured once, But we haven't found a better solution yet.)

Timestampserializer.java

 Packagecom.cici.utils;Importjava.io.IOException;ImportJava.sql.Timestamp;ImportJava.text.SimpleDateFormat;ImportCom.cici.example.view.domain.DateTime;ImportCom.fasterxml.jackson.core.JsonGenerator;Importcom.fasterxml.jackson.core.JsonProcessingException;ImportCom.fasterxml.jackson.databind.JsonSerializer;ImportCom.fasterxml.jackson.databind.SerializerProvider;/** * @authorcc * Write a serializer for each class*/ Public classTimestampserializerextendsJsonserializer<timestamp>{@Override Public voidSerialize (Timestamp dateTime, Jsongenerator generator, Serializerprovider provider)throwsIOException, jsonprocessingexception {simpledateformat SDF=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); String datetimeformated=Sdf.format (dateTime);    Generator.writestring (datetimeformated); }}
View Code

Then configure the Getter method on the property

@JsonSerialize (Using=timestampserializer.  Class)    Timestamp nowdate;      Public Timestamp getnowdate () {        return  nowdate;    }

These are the two pits that have been stepped on.

This time the request and return are as follows

Do the request body and the response body with JSON by the way, the small plum that returns a long type timestamp problem with the date type is complete.

Receive and respond to JSON-formatted data with SPRINGMVC @requestbody and @responsebody

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.