Spring Boot,Spring MVC JSON RequestBody:未知属性被忽略 [英] Spring Boot, Spring MVC JSON RequestBody: Unknown property ignored

查看:275
本文介绍了Spring Boot,Spring MVC JSON RequestBody:未知属性被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发一个JSON Web服务,以通过@RequestBody批注接收数据.如果请求中包含的属性与反序列化的Bean不匹配,则我们期望使用HTTP 400(错误请求)响应,但是该属性将被忽略.这是一个示例:

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;
}

发布时

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

我们收到HTTP 200响应.在这种情况下,如何使Spring MVC返回HTTP 400?

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?.

因为该问题询问缺少预期属性时如何返回400.

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

推荐答案

我找到了答案:

将其放入application.properties:

Put this into application.properties:

spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true

以下是相关文档: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆