membersound
membersound

Reputation: 86935

How to accept JSON POST parameters as @RequestParam in Spring Servlet?

I'm trying to create a POST servlet that should be called with JSON request. The following should work, but does not. What might be missing?

@RestController
public class MyServlet {
    @PostMapping("/")
    public String test(@RequestParam String name, @RequestParam String[] params) {
        return "name was: " + name;
    }
}

JSON POST:

{
   "name": "test",
   "params": [
      "first", "snd"
   ]
}

Result: name is always null. Why?

"Response could not be created: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present"

Upvotes: 4

Views: 9269

Answers (2)

In addition to @stzoannos answer, if you do not want to create POJO for json object, you can use google GSON library to parse json into JsonObject class, which allow to work with parameters through same as get and set methods.

JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
return "name is: " + jsonObj.get("name").getAsString();

Upvotes: 0

stzoannos
stzoannos

Reputation: 938

In general I don't pass a request param in a POST method. Instead, I am using a DTO to pass it in the body like:

@RequestMapping(value = "/items", method = RequestMethod.POST)
    public void addItem(@RequestBody ItemDTO itemDTO) 

Then, you need to create the ItemDTO as a POJO with the necessary fields.

Upvotes: 9

Related Questions