I am working with Java Spring framework and receive a JSON on input. It consists of an array of thousands of MyObjects. I would like the application to throw exception if one of the MyObjects or AnotherObjects fails a constraint (@NotNull or @Size).
So far, the application throws NullPointerException once it is accessing the null field when doing something with the object - not during its construction.
My question is:
Is there a way to check the constraints of nested JSON objects preferrably with annotation?
The JSON looks like:
{
"myObjects": [
{
"code": "PQ",
"another_objects": [
{
"attr1": "value1",
"attr2": "value2",
"attrN": "valueN"
},
{
"attr1": "value1",
"attr2": "value2",
"attrN": "valueN"
}
]
},
{
...
}
]
}
The servlet looks like:
@RequestMapping(value = ...)
public final void doSomething(@Valid @RequestBody MyObjectWrapper wrapper) {
// do something very time-heavy here
}
The objects are defined as follows:
public class MyObjectWrapper {
private List<MyObject> myObjects;
public List<MyObject> getMyObjects() {
return myObjects;
}
public void setMyObjects(List<MyObjects> myObjects) {
this.myObjects = myObjects;
}
}
And the MyObject class:
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 */
}
The AnotherObjects is similar but consists of Strings only.