3

It seems that GSON silently ignores when a JSON string contains field names that don't match the target POJO class. One solution outlined here suggests to use annotations to mark "required" fields to have GSON fail when de-serializing strings that don't contain fields.

But we defined that our POJOs must be "exact" matches (when we allow for incoming objects to be null, they must be declared as Optional field in the POJO - and we have a special type adapter that turns nulls into Optional.empty() instances). Therefore all fields in the POJO are mandatory. And null isn't a valid value.

Following the guidance in that question I linked to, it seems that the only way of having gson fail while parsing: to do a full "deep reflection" scan of the object created by de-serialization process and check if any of the Optional fields are null.

Or maybe - I am missing something and there is an easier way to have gson tell me when our JSON strings contain bad field names?

( background: we just ran into a problem because of wrong field name deep down in a nested structure - leading to null objects where we didn't expect them )

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 2
    https://github.com/google/gson/issues/188 looks related. – Andy Turner Dec 11 '17 at 08:16
  • See also [How to check if JSON is valid in Java using GSON](https://stackoverflow.com/questions/43233898/how-to-check-if-json-is-valid-in-java-using-gson/47890960#47890960) in gson strict parsing workaround. – Vadzim Jul 05 '19 at 10:07
  • 1
    See also [Gson optional and required fields](https://stackoverflow.com/questions/21626690/gson-optional-and-required-fields) on ensuring required fields. – Vadzim Jul 05 '19 at 10:16

1 Answers1

4

Turns out: this "deficiency" is really a core design point of gson: it is a JSON parser. Validation is not within the scope of gson.

Therefore the "correct" answer is to use java bean validation annotations and to put some implementation framework (for example the hibernate validator or apache bval) in place.

Alternatively, it is possible to register a special type adapter when creating the gson instance. This type adapter uses reflection to override an internal map with a bit of checking code - allowing for a relatively "clean" solution which leads to gson throwing an exception when running into "unknown" fields. ( thanks to Andy Turner for pointing to the corresponding github issue tracker entry --- code can be found there)

GhostCat
  • 137,827
  • 25
  • 176
  • 248