soham
soham

Reputation: 39

how to create json response in spring boot java like this as shown when the following attributes are not present in json request

I am creating an controller where there is certain attributes in json which is an doing in postman a POST request like this if all attributes are posted then its fine this is the image if all attributes are there in json

if one then is missing then it would look like this enter image description here

i want this response when some attribute is missing how to implement this enter image description here

Upvotes: 1

Views: 293

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

This is normally implemented in two steps:

  1. Implement a validation mechanism for the method that handles the incoming request. Normally you would throw an exception here if the input is incorrect, in your example a missing JSON key.

  2. Implement a global error handler that will process the exception from point 1 and format the response as JSON.

For point 1 the usual choice is the Java Bean Validation framework because it's integrated with Spring Boot and allows to define validation constraints with annotations like @NotEmpty. You can take a look at this example.

For point 2 the usual choice is @RestControllerAdvice or @ControllerAdvice. You would have to understand your service web server setup to implement it properly e.g. it might behave differently if you use Spring WebFlux.

Upvotes: 1

Related Questions