Senior
How to accept a POST request with JSON on the Spring side? When does JSON convert to DTO?
sobes.tech AI
Answer from AI
In Spring, to accept a POST request with JSON, the @RequestBody annotation is usually used in the controller. Spring automatically deserializes JSON into a DTO using Jackson (or another configured JSON parser).
Example:
@PostMapping("/users")
public ResponseEntity<String> createUser(@RequestBody UserDto userDto) {
// userDto already contains data from JSON
// processing logic
return ResponseEntity.ok("User created");
}
The conversion of JSON to DTO occurs during request processing, before entering the controller method. Spring MVC uses HttpMessageConverter (for example, MappingJackson2HttpMessageConverter), which reads the request body, parses the JSON, and maps it to the DTO object.
If the JSON is invalid or does not match the DTO structure, Spring will return a 400 Bad Request error.