Spring MVC : post request and json object with arr

2019-05-09 13:59发布

问题:

I'm trying to retrieve parameters from a http POST request with Spring MVC.

The request contains the following json object (content-type : application/json), which itself contains an array of customObjects :

{  
   "globalId":"338",
   "lines":[  
      {  
         "id": "someId",
         "lib":"blabla",
        ...

      }
   ]
}

Here's the code I'm trying to use :

  @RequestMapping(method = RequestMethod.POST, value = "/valider")
  @ResponseBody
  public void valider(final HttpServletRequest request, @RequestParam("globalId") final String globalId, @RequestParam("lines") final MyCustomObject[] lines) {

All I'm getting is a "bad request" error (http 400).

Is it possible to separately retrieve the two parameters "globalId" and "lines" ? Or since they are in the same json object, it has to be treated has a single parameter ? How do you proceed when you have more than one parameter in a Post request ?

回答1:

I think you're looking for something like `@RequestBody. Create a class to represent your JSON data. In your case, this class will contain two member variables - globalId as a string and lines as an array of the object it represents. Then in your controller method, you will use the @RequestBody annotation on this class type so that Spring will be able to convert the JSON into object. Check the examples below.

http://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/

JQuery, Spring MVC @RequestBody and JSON - making it work together

http://www.techzoo.org/spring-framework/spring-mvc-requestbody-json-example.html



回答2:

create model object to map your Json data

class DLibrary{
    int id;
    String lib;
    //getters/setters
}
class GLibrary{
   int globalId;
   List<DLibrary> lines;
   //getters/setters
}

Replace your controller code with below

@RequestMapping(method = RequestMethod.POST, value = "/valider")
@ResponseBody
public void valider(@RequestBody GLibrary gLibrary) {

@RequestBody annotation will map Json to Java Object implicitly. To achieve this spring must require jackson-core and jackson-mapper library included in your application and your Java class should have getter and setters i.e it must follow bean standards.



回答3:

Indeed, I have to use @RequestBody to get the JSON object.

Quick summary, depending on how the parameters are passed in the http POST body request :

  1. one JSON object (Content-Type: application/json), use @RequestBody to map the json object to a java object

  2. multiple parameters (Content-Type: application/x-www-form-urlencoded), use @RequestParam for each parameter