I'm attempting to write a simple class that will validate a JSON input string if it can be converted to a target JAVA object.
The validator should fail if any unknown field is found in the input JSON String.
It all works as expected except until I annotate the B object inside the A class with @JsonUnwrapped
, then the object mapper will silently ignore the unknown properties without failing.
Here is my code :
Class A :
public class A implements Serializable{
protected String id;
protected String name;
protected @JsonUnwrapped B b;
public A(){
}
public A(String id, String name, B b) {
super();
this.id = id;
this.name = name;
this.b = b;
}
//GETTERS/SETTERS
}
Class B :
public class B {
protected String innerId;
protected String innerName;
public B(){
}
public B(String innerId, String innerName) {
super();
this.innerId = innerId;
this.innerName= innerName;
}
//GETTERS/SETTERS
}
The validator class:
public class JsonValidator{
public boolean validate(){
ObjectMapper mapper = new ObjectMapper();
//mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
try {
mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
A a = mapper.readValue(
JsonValidatorBean.class.getResourceAsStream("sample.json"),
A.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The JSON to validate :
{
"id": "aaaa",
"naome": "aaa",
"innerId" : "bbbb",
"innerName" : "bbb"
}
I'm using Jackson 2.1
I'm expecting this code to fail on the unknown property "naome" but it doesn't it just gets ignored.
If I remove the @JsonUnwrapped
and adapt the Json to having an embedded object, the above code fails as expected.
Any ideas?