3

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?

kaya3
  • 47,440
  • 4
  • 68
  • 97
ufasoli
  • 1,038
  • 2
  • 19
  • 41

1 Answers1

3

Yes, this is true statement. Due to logic needed to pass down unwrapped properties from parent context, there is no way to efficiently verify which properties might be legitimately mapped to child POJOs (ones being unwrapped), and which not.

There is an RFE to try to improve things, to catch unmappable properties but current versions (up to and including 2.2) can not do both unwrapping and guard against unmappable properties.

StaxMan
  • 113,358
  • 34
  • 211
  • 239