Spring MVC : post request and json object with array : bad request

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 ?


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


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 ie it must follow bean standards.


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 :

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

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

  • 链接地址: http://www.djcxy.com/p/8598.html

    上一篇: REST与Spring和Jackson完全数据绑定

    下一篇: Spring MVC:发布请求和包含数组的json对象:错误的请求