'How to make GSON fail on unknown properties

I need GSON mapper to throw an exception if json contains unknown fields. For example if we have POJO like

public class MyClass {
    String name;
}

and json like

{
    "name": "John",
    "age": 30
}

I want to get some sort of message that json contains unknown field (age) that can not be deserialized.

I know there is out-of-box solution in Jackson mapper, but in our project we have been using Gson as a mapper for several years and using Jackson ends up in conflicts and bugs in different parts of project, so it is easier for me to write my own solution than using Jackson.

In other words, I want to know if there is some equivalent to Jackson's DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES in Gson. Or maybe if it can be done using Gson's DeserializationStrategy other than using reflections



Solution 1:[1]

I believe you cannot do it automatically with Gson.

I had to do this in a project at work. I did the following:

Gson GSON = new GsonBuilder().create();
(static final) Map<String, Field> FIELDS = Arrays.stream(MyClass.class.getDeclaredFields())
    .collect(Collectors.toMap(Field::getName, Function.identity()));

JsonObject object = (JsonObject) GSON.fromJson(json, JsonObject.class);

List<String> objectProperties = object.entrySet().stream().map(Entry::getKey).collect(Collectors.toList());
List<String> classFieldNames = new ArrayList<>(FIELDS.keySet());

if (!classFieldNames.containsAll(objectProperties)) {
    List<String> invalidProperties = new ArrayList<>(objectProperties);
    invalidProperties.removeAll(classFieldNames);
    throw new RuntimeException("Invalid fields: " + invalidProperties);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bonnev