Вам просто нужно аннотировать вашего клиента с помощью @RequestBody
и @Valid
в методе rest. Вот пример:
@RestController
@RequestMapping("/api/client")
public class ClientController {
@PostMapping
public ResponseEntity createNewClient(@RequestBody @Valid Client client) {
// insert client
return new ResponseEntity(HttpStatus.CREATED);
}
}
Если данные JSON будут недействительными, метод выдаст MethodArgumentNotValidException
. Вы можете справиться с этим так:
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleArgumentNotValidException(
MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
BindingResult bindingResult = ex.getBindingResult();
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errors.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}