Harry Harry - 5 months ago 67
Java Question

POSTing JSON object to Spring Controller and validating with nested objects

I'm trying to validate nested objects being POSTed through jQuery.

Here are my objects:

public class One {

@Valid
@NotNull
Two two;

public Two getTwo() {
return two;
}

public void setTwo(Two two) {
this.two = two;
}

}


and

public class Two {

@NotNull
private String property;

public String getProperty() {
return property;
}

public void setProperty(String property) {
this.property = property;
}

}


and here is my controller:

@RequestMapping(value="/", method=RequestMethod.POST)
@ResponseBody
public String test(@Valid One one) {
return "Success";
}


However, I am POSTing the following JSON object:

{
"two": {
"property": "test"
}
}


and I get the error:
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]


Is there something wrong with my JSON structure or is there something I am missing?

EDIT
Here is the jQuery ajax call:

$.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);
});

Answer

Change your method to:

@RequestMapping(value="/", method=RequestMethod.POST, consumes={"application/json"})
public String test(@RequestBody One one)
Comments