Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reject deserialization of unrecognized properties with JSON-B

I am attempting to migrate the implementation details of some JSON databinding code to use the Java EE 8 JSON-B APIs instead of Jackson.

In order to match the default behavior of Jackson, I want to reject any attempts to deserialize a JSON payload into a POJO when the JSON payload contains unrecognized attributes.

For example, if I have the following JSON data:

{ 
  "name": "Bob",
  "extraProp": "Something"
}

And I have the following Java Object that models this data as:

public class Thing {
    public String name;
    // no mention of "extraProp"
}

How would I reject attempts to bind the above JSON data into the above POJO?

If I try the following, the Thing object gets created without error (here I want an error to occur):

Jsonb jsonb = JsonbProvider.provider()
                    .create()
                    .build();
Thing t = jsonb.fromJson("{\"name\":\"Bob\",\"extraProp\":\"Something\"}", Thing .class);
like image 910
Andy Guibert Avatar asked Sep 21 '17 15:09

Andy Guibert


1 Answers

Unfortunately, as near as I can tell, the JSON-B spec doesn't allow this.

Section 3.18 says

When JSON Binding implementation during deserialization encounters key in key/value pair that it does not recognize, it should treat the rest of the JSON document as if the element simply did not appear, and in particular, the implementation MUST NOT treat this as an error condition.

However, the reference implementation seems to support a property called 'jsonb.fail-on-unknown-properties' that you can set to enable this. Johnzon, another implementation, also seems to, but it's not documented (yet?). Its property is named 'johnzon.fail-on-unknown-properties'.

like image 126
Matt Drees Avatar answered Oct 09 '22 05:10

Matt Drees