Spring JSON request body not mapped to Java POJO

You can do it in many ways, Here i am going to do it in below different ways-

NOTE: request data shuld be {"customerInfo":{"firstname":"xyz","lastname":"XYZ"}}

1st way We can bind above data to the map as below

@RequestMapping(value = "/send", headers = "Accept=application/json", method = RequestMethod.POST)
public void sendEmails(@RequestBody HashMap<String, HashMap<String, String>> requestData) {

    HashMap<String, String> customerInfo = requestData.get("customerInfo");
    String firstname = customerInfo.get("firstname");
    String lastname = customerInfo.get("lastname");
    //TODO now do whatever you want to do.
}

2nd way we can bind it directly to pojo

step 1 create dto class UserInfo.java

public class UserInfo {
    private CustomerInfo customerInfo1;

    public CustomerInfo getCustomerInfo1() {
        return customerInfo1;
    }

    public void setCustomerInfo1(CustomerInfo customerInfo1) {
        this.customerInfo1 = customerInfo1;
    }
}

step 1. create another dto classCustomerInfo.java

class CustomerInfo {
        private String firstname;
        private String lastname;

        public String getFirstname() {
            return firstname;
        }

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

        public String getLastname() {
            return lastname;
        }

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

step 3 bind request body data to pojo

 @RequestMapping(value = "/send", headers = "Accept=application/json", method = RequestMethod.POST)
    public void sendEmails(@RequestBody UserInfo userInfo) {

        //TODO now do whatever want to do with dto object
    }

I hope it will be help you out. Thanks


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.


The formatting on this is terrible, but this should work for jackson configuration.

<!-- Use Jackson for JSON conversion (POJO to JSON outbound). -->
<bean id="jsonMessageConverter"
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> 

<!-- Use JSON conversion for messages -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

ALso, as mentioned in a comment, your JSON is wrong for your object.

{"firstname":"xyz",‌​"lastname":"XYZ"}

does appear to be the correct JSON for your object.