Spring rest json post null values

I have a Spring rest endpoint that makes a simple welcome app. It should accept {"name": "something"} and return "Hello, something".

My controller:

@RestController
public class GreetingController { 

    private static final String template = "Hello, %s!";

    @RequestMapping(value="/greeting", method=RequestMethod.POST)
    public String greeting(Person person) {
        return String.format(template, person.getName());
    }

}

      

Person

public class Person {

    private String name;

    public Person() {
        this.name = "World";
    }

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

      

When I make a request to a service like

curl -X POST -d '{"name": "something"}' http://localhost:8081/testapp/greeting

      

I get

Hello, World!

      

It looks like this is not deserializing the json on the Person object as expected. It uses the default constructor and then doesn't set the name. I found this: How to create a POST request in REST to accept JSON input? so I tried adding @RequestBody to the controller but that throws some error regarding "Content type 'application / x-www-form-urlencoded; charset = UTF-8' is not supported". I see it is described here: Content type 'application / x-www-form-urlencoded; charset = UTF-8 'not supported for @RequestBody MultiValueMap which suggests to remove @RequestBody

I tried removing the default constructor which it doesn't like either.

This question covers null REST webservice using Spring MVC returning null when posting JSON , but it suggests adding @RequestBody, but that conflicts with above ...

+3


source to share


2 answers


You must set @RequestBody

to specify Spring what should be used to set the parameter person

.



 public Greeting greeting(@RequestBody Person person) {
    return new Greeting(counter.incrementAndGet(), String.format(template, person.getName()));
} 

      

+8


source


You must set ' produces ' using @RequestMapping (value = "/ greeting", method = RequestMethod.POST)

use below code



@RequestMapping(value="/greeting", method=RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
 public String greeting(Person person) {
        return String.format(template, person.getName());
    }

      

+1


source







All Articles