1

I have a Spring MVC project and I have configured the jackson library to automatically transform the response (java object) to a json and it works in GET requests as following.

    @RequestMapping(method = RequestMethod.GET)
public @ResponseBody Orders createOrder(Model model){

            Orders orders = new Orders();
            //Populate orders.....

    return orders;
}

But when a I try to process the POST request and get the object from the json's request, I get the error "400 Bad Request" as Spring cannot create the object Orders from the json. I put the same json file that the GET method response, so I suppose that the file is well formatted.

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> createOrder(@RequestBody Orders orders){

    LOG.info(orders.toString());

    return new ResponseEntity<String>("", HttpStatus.CREATED);
}

If I change the @RequestBody class to String (createOrder(@RequestBody String orders)), the POST request is well processed.

Do I have to create a mapper that maps the input json to the class Order?

UPDATE: I have created the most simple example to try it and I receive the error 400. Exmaple:

Domain: Home.java

public class Home {
    private String address = "Calle mármoles";

    public Home(){

    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Controller:

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> createOrder2(@RequestBody Home orders){
    return new ResponseEntity<String>("{}", HttpStatus.CREATED);
}

JSON (POST):

{
  address: "Prueba"
}

[SOLVED]

I missed to put "" in the name of the parameter name.

Dave Newton
  • 152,765
  • 23
  • 240
  • 286
er_benji
  • 305
  • 3
  • 9
  • How do you call your post method? Is the body of the request consisted only of the json from the GET? – Avi Feb 18 '14 at 12:00
  • Yes, the body has only the JSON. – er_benji Feb 18 '14 at 12:05
  • 1
    It's probably best that you put your solution as an answer, so that A) This question is properly marked as being solved and B) It's obvious to other people who may have a similar problem in the future what was wrong in your case. – Edd Feb 18 '14 at 12:33
  • GET with request body may not work at all, depending on the container and client, see [HTTP GET with request body](http://stackoverflow.com/questions/978061/http-get-with-request-body) – Arne Burmeister Feb 18 '14 at 20:49

1 Answers1

0

[SOLVED]

I missed to put "" in the name of the parameter name.

Besides, the class has to have a default blank constructor in order to allow the jackson library creating the object.

er_benji
  • 305
  • 3
  • 9