我正在使用Java Spring框架并在输入上接收JSON。它由数千个MyObjects
组成。如果其中一个MyObjects
或AnotherObjects
未通过约束(@NotNull
或@Size
),我希望应用程序抛出异常。
到目前为止,应用程序在对对象执行操作时访问NullPointerException
字段时会抛出null
- 而不是在构造期间。
我的问题是:
有没有办法优先使用注释来检查嵌套JSON对象的约束?
JSON看起来像:
{
"myObjects": [
{
"code": "PQ",
"another_objects": [
{
"attr1": "value1",
"attr2": "value2",
"attrN": "valueN"
},
{
"attr1": "value1",
"attr2": "value2",
"attrN": "valueN"
}
]
},
{
...
}
]
}
servlet看起来像:
@RequestMapping(value = ...)
public final void doSomething(@Valid @RequestBody MyObjectWrapper wrapper) {
// do something very time-heavy here
}
对象定义如下:
public class MyObjectWrapper {
private List<MyObject> myObjects;
public List<MyObject> getMyObjects() {
return myObjects;
}
public void setMyObjects(List<MyObjects> myObjects) {
this.myObjects = myObjects;
}
}
MyObject类:
public class MyObject {
@NotNull
@NotEmpty(message = ...)
List<AnotherObject> anotherObjects;
@NotNull
@Size(min = 2, max = 2, message = ...)
String code;
@JsonCreator
public MyObject(@JsonProperty("another_objects") List<AnotherObjects> anotherObjects,
@JsonProperty("code") String code) {
this.code = code;
this.anotherObjects = anotherObjects;
}
/* getters and setters */
}
AnotherObjects类似,但仅包含字符串。
答案 0 :(得分:2)
将@Valid
添加到包装器的嵌套对象
public class MyObjectWrapper {
@Valid
private List<MyObject> myObjects;
public List<MyObject> getMyObjects() {
return myObjects;
}
public void setMyObjects(List<MyObjects> myObjects) {
this.myObjects = myObjects;
}
}