Spring receives multiple object parameters in JSON format (workaround)

Source: Internet
Author: User

If you use spring MVC to communicate with clients and use the JSON data format completely, you need to define a requestmapping as follows

@Controller  Public class testcontroller{  @RequestMapping ("\test")  @ResponseBody  public  Retureresult Test (@RequestBody user user) {    returnnew  returnresult ();  }  } 

This allows the JSON-formatted data to be converted to the specified object user, such as {name: ' Test '},name the property value of the user class, or it can return JSON-formatted data.

But sometimes when we receive JSON-formatted data, we may need to convert it to multiple objects, which is not supported by the direct definition of multiple arguments in a method variable, and the following is an error. The reason is that the body of request is read in the form of a stream, and once it has been read, it cannot be read again.

  @Controller  public  class   testcontroller{@RequestMapping ( "\test" ) @ Responsebody  public   Retureresult Test (@RequestBody User user, @RequestBody address) { return  new    Returnresult (); }  }

You can use a workaround to do this at this point.

Add a wrapper class to the Testcontroller.java file

@Controller  Public class testcontroller{  @RequestMapping ("\test")  @ResponseBody  public  Retureresult Test (@RequestBody Param Param) {    returnnew  returnresult ();  }class  param{  public  user user;    Public address address;  }

Note: A property in a class must be a property in Public;param only more than the object in JSON, not less.

The transferred JSON data format changes to {user:{name: "Test"},address:{location: "Xinhualu"}}.

Because just adding a wrapper class to the TestController does not affect other classes and the model class that is already defined, it is very convenient to achieve the purpose of receiving multiple object parameters.

Spring receives multiple object parameters in JSON format (workaround)

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.