Spring JSON request body not mapped to Java POJO

前端 未结 5 1018
终归单人心
终归单人心 2020-12-29 04:54

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

5条回答
  •  感情败类
    2020-12-29 05:39

    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> requestData) {
    
        HashMap 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

提交回复
热议问题