Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot, Spring MVC JSON RequestBody: Unknown property ignored

we are developing a JSON web service to receive data via the @RequestBody annotation. In case a property is included in the request that does not match with the deserialized bean, we expect an HTTP 400 (Bad request) response, but instead the property is simply ignored. Here is an example:

@RestController
@Slf4j
public class TestController {

  @RequestMapping(method = RequestMethod.POST, value = "/query")
  public void parse(@RequestBody Query query) {
    log.info("Received query: {}", query.toString());
  }
}


@Data
class Query {
  private String from;
  private String to;
}

When posting

{ "from" : "123", "to": "456", "foo" : "bar" }

we get a HTTP 200 response. How can we make Spring MVC return HTTP 400 in this case?

Any help or pointers are highly appreciated.

Note that this is different from this question: How to return 400 HTTP error code when some property of a RequestBody parameter is null?.

Since that question asks how to return 400 when an expected property is absent.

like image 860
user152468 Avatar asked Mar 11 '16 10:03

user152468


People also ask

Is @RequestBody mandatory?

requestBody consists of the content object, an optional Markdown-formatted description , and an optional required flag ( false by default). content lists the media types consumed by the operation (such as application/json ) and specifies the schema for each media type. Request bodies are optional by default.

Is @RequestBody optional?

Annotation Type RequestBodyOptionally, automatic validation can be applied by annotating the argument with @Valid . Supported for annotated handler methods.

Is @RequestBody required with @RestController?

Remember, we don't need to annotate the @RestController-annotated controllers with the @ResponseBody annotation since Spring does it by default.

How do I ignore fields in JSON request?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.


1 Answers

Put this into application.properties:

spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true

Here are the relevant docs: Customize the Jackson ObjectMapper

like image 133
user152468 Avatar answered Sep 28 '22 05:09

user152468