Spring JSON request body not mapped to Java POJO

Y. Chen :

I'm using Spring to implement a RESTful web service. One of the endpoints takes in a JSON string as request body and I wish to map it to a POJO. However, it seems right now that the passed-in JSON string is not property mapped to the POJO.

here's the @RestController interface

@RequestMapping(value="/send", headers="Accept=application/json", method=RequestMethod.POST)
public void sendEmails(@RequestBody CustomerInfo customerInfo);

the data model

public class CustomerInfo {
    private String firstname;
    private String lastname; 
    public CustomerInfo() {
        this.firstname = "first";
        this.lastname = "last";
    }

    public CustomerInfo(String firstname, String lastname)
    {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname(){
        return firstname;
    }

    public void setFirstname(String firstname){
        this.firstname = firstname;
    }

    public String getLastname(){
        return lastname;
    }

    public void getLastname(String lastname){
        this.lastname = lastname;
    }
}

And finally my POST request:

{"CustomerInfo":{"firstname":"xyz","lastname":"XYZ"}}

with Content-Type specified to be application/json

However, when I print out the object value, the default value("first" and "last") got printed out instead of the value I passed in("xyz" and "XYZ")

Does anyone know why I am not getting the result I expected?

FIX

So it turned out that, the value of request body is not passed in because I need to have the @RequestBody annotation not only in my interface, but in the actual method implementation. Once I have that, the problem is solved.

Y. Chen :

So it turned out that, the value of request body is not passed in because I need to have the @RequestBody annotation not only in my interface, but in the actual method implementation. Once I have that, the problem is solved.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=446821&siteId=1