【发布时间】:2015-06-13 18:39:18
【问题描述】:
我有以下端点:
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
public class TestController {
@RequestMapping(value = "/persons", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Integer> create(@RequestBody Person person) {
// create person and return id
}
}
今天如果我收到这样一个未知字段的请求:
{
"name" : "Pete",
"bijsdf" : 51
}
我创建人并忽略未知字段。
如何检查是否存在未知字段,然后返回错误请求?
【问题讨论】:
-
您使用的是什么 JSON 库?我认为这是杰克逊的默认设置
-
嗨 Neil,是的,我使用的是 jackson 2.5.0
-
是的,Jackson 会处理这个问题。你的
Person类是否用@JsonIgnoreProperties(ignoreUnknown = true)注释? -
我的 Person 类上没有注释
-
检查一下:fasterxml.github.io/jackson-annotations/javadoc/2.5/com/…
ignoreUnknown的默认值为false。这意味着 Jackson(我正在查看 2.5.0 文档)默认情况下会为缺少的字段抛出异常。
标签: java validation rest spring-mvc jackson