I have a simple POST
servlet and want to inject only one single property of a JSON
request:
@RestController
public class TestServlet {
@PostMapping(value = "/test", consumes = APPLICATION_JSON_VALUE)
public String test(@Valid @NotBlank @RequestBody String test) {
return test;
}
}
Request:
{
"test": "random value",
"some": "more"
}
Result: the test
parameter contains the whole json, not the parameter value only. Why? How can I achieve this without having to introduce an extra Bean?
You can't expect Spring to guess that you want to parse the json to extract the "test" field.
If you don't want an extra bean, use a Map<String, String>
and get the value with "test" key :
@RestController
public class TestServlet {
@PostMapping(value = "/test", consumes = APPLICATION_JSON_VALUE)
public String test(@Valid @NotBlank @RequestBody Map<String, String> body) {
return body.get("test");
}
}