问题
I have a spring rest api which gets json data and binds to a pojo GetData. Whenever i recieve unknown fields it doesnt fail or throw any exception. My requirement here is it should throw a error when it receives unknown fields in json data.
public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) {
Below is my Pojo GetData
public class GetData{
@JsonProperty("deviceID")
@Pattern(regexp="^[\\p{Alnum}][-\\p{Alnum}\\p{L}]+[\\p{Alnum}]$",message = "Not a valid Device Id")
private String deviceID;
@JsonProperty("Coordinates")
@Pattern(regexp="^[\\p{Alnum}\\-][\\.\\,\\-\\_\\p{Alnum}\\p{L}\\s]+|",message = "Coordinates are not valid")
private String coordinates;}
Below is my json request.
{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
}
Now if i send a request with an extra field say country. It doesn't throw any error.
{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
"country" : "dsasa"
}
Please suggest how can i have an error for unknown properties being sent in a json request
回答1:
You can try out any one of the below implementations, it works for me. You will have to override one more method from ResponseEntityExceptionHandler
or by using ExceptionHandler
.
1. By Overriding Method of ResponseEntityExceptionHandler
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);
//Other Handlers
// Handle 400 Bad Request Exceptions
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
log.info(ex.getLocalizedMessage() + " ",ex);
final CustomErrorMessage errorMessage = new CustomErrorMessage(ex.getLocalizedMessage(), InfoType.ERROR, HttpStatus.BAD_REQUEST, ex.fillInStackTrace().toString());
return handleExceptionInternal(ex, errorMessage, headers, errorMessage.getStatus(), request);
}
//Other Handlers
}
Apart from above implementation you can try out the below one also, if you want to throw error only if unrecognised properties are present in request payload or empty property and empty value is present like below JSON
{
"":""
}
2. Using ExceptionHandler
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GenericExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GenericExceptionHandler.class);
@ExceptionHandler(value = {UnrecognizedPropertyException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ResponseEntity<Object> handleUnrecognizedPropertyException(UnrecognizedPropertyException ex) {
log.info(ex.getLocalizedMessage() + " ",ex);
final String error = "JSON parse error: Unrecognized field " + "[ " + ex.getPropertyName() + " ]";
final CustomErrorMessage errorMessage = new CustomErrorMessage(error, InfoType.ERROR, HttpStatus.BAD_REQUEST);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
}
}
Note : For above both implementations to work properly, you need to add the below line in your application.properties
file.
spring.jackson.deserialization.fail-on-unknown-properties=true
Hope this will help you :)
回答2:
You need to configure your ObjectMapper
to handle such cases:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
回答3:
Alternatively you can use:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = false)
public class GetData {
}
来源:https://stackoverflow.com/questions/43120292/how-do-i-throw-a-error-on-unknown-fields-in-json-request-to-spring-restapi