How to get the object from an API REST with Spring MVC

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.


[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.

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

上一篇: Spring REST jackson不会在POST请求上编组

下一篇: 如何使用Spring MVC从API REST获取对象