REST webservice using Spring MVC returning null when posting JSON

Developing a REST web service using Spring MVC that accepts a JSON request body. And to process the received message further. Iam using the following: Eclipse, Tomcat, Spring 3.0.1, Jackson lib, Curl to test webservice


    `curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"fname":"my_firstname" , "lname":"my_lastname"}' http://localhost:8080/SpringMVC/restful`
      

return

"Saved person: null null"
      

My controller class



        import com.samples.spring.Person;

    @Controller
    public class RestController {

    @RequestMapping(value="{person}", method = RequestMethod.POST)
    @ResponseBody
        public String savePerson(Person person) {
             // save person in database
            return "Saved person: " + person.getFname() +" "+ person.getLname();
        }


      

My human class




       package com.samples.spring;

    public class Person {

        public String fname;
        public String lname;

        public String getFname() {
            return fname;
        }
        public void setFname(String fname) {
            this.fname = fname;
        }
        public String getLname() {
            return lname;
        }
        public void setLname(String lname) {
            this.lname = lname;
        }
    }


      

+1


source to share


2 answers


try adding @RequestBody



@RequestMapping(value="{person}", method = RequestMethod.POST)
@ResponseBody
    public String savePerson(@RequestBody Person person) {
         // save person in database
        return "Saved person: " + person.getFname() +" "+ person.getLname();
    }

      

+5


source


try adding a constructor to the Person class:



public Person(String fname, String lname) {
    this.fname = fname;
    this.lname = lname;
}

      

0


source







All Articles