【发布时间】:2016-06-18 02:44:08
【问题描述】:
我正在尝试验证通过 jQuery 发布的嵌套对象。
这是我的对象:
public class One {
@Valid
@NotNull
Two two;
public Two getTwo() {
return two;
}
public void setTwo(Two two) {
this.two = two;
}
}
和
public class Two {
@NotNull
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
这是我的控制器:
@RequestMapping(value="/", method=RequestMethod.POST)
@ResponseBody
public String test(@Valid One one) {
return "Success";
}
但是,我正在发布以下 JSON 对象:
{
"two": {
"property": "test"
}
}
我得到错误:Field error in object 'one' on field 'two': rejected value [null]; codes [NotNull.one.two,NotNull.two,NotNull.com.test.Two,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [one.two,two]; arguments []; default message [two]]; default message [may not be null]
我的 JSON 结构有问题还是缺少什么?
编辑 这是 jQuery ajax 调用:
$.ajax({
type: 'POST',
url: 'my-url-here',
data: JSON.stringify({"one":{"two":{"property": "test"}}}),
dataType: "json",
contentType: 'application/json'
}).done(function(data) {
console.log(data);
});
【问题讨论】:
-
除了您发布的 JSON 对象外没有任何问题。错误正是它应该是的。您收到的 One 必须有一个对象 Two 作为 NotNull。而你只是发送一个对象二。你希望它如何通过?尝试发送:
{"one":{"two":{"property": "test"}}} -
@JorgeCampos 这会产生相同的结果
-
将您的
@RequestMapping更改为@RequestMapping(value="/", method=RequestMethod.POST, consumes = {"application/json"}) -
@JorgeCampos 仍然出现相同的错误(对于您推荐的结构和我的原始结构)
-
那么你的弹簧设置应该有问题。
标签: java json spring validation