7

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);
Andy Guibert
  • 41,446
  • 8
  • 38
  • 61
  • When you evolve APIs, you may want to add fields that not all clients understand, yet. So most modern tools intentionally and decidedly ignore additional fields by default to ease migrations. If you just want to replace Jackson, you should probably reconsider to drop that requirement. – rü- Jun 15 '19 at 06:23

1 Answers1

8

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'.

Matt Drees
  • 443
  • 3
  • 11
  • FYI, Jackson [obnoxiously] does the opposite by default. So if your client includes an unknown property, rather than ignoring it, it throws an error. – Jonathan S. Fisher Jan 03 '20 at 19:18
  • Since Eclipse Yasson v2.0, the inline javadoc was changed to say "JsonbException is risen on unknown property. Default is true even if not set in json config" (in method ``getConfigFailOnUnknownProperties()``), BUT interestingly enough, the default behavior present in the code actually remains to IGNORE the unknown properties as @matt-drees already explained... – leonidos79 Oct 04 '21 at 14:30