I want to deserialize a field and be sure that no errors occurred, every field was read. If something is wrong with json file, I want to know.
private static class A {
int x;
}
public static void main(String[] args) {
Gson gson = new Gson();
A a;
try {
Reader reader = new StringReader("{\"y\":10}");
a = gson.getAdapter(A.class).fromJson(reader);
} catch (IOException | JsonSyntaxException e) {
System.out.println(e.getMessage());
return;
}
}
In this example I changed field name in json string from x
to y
. I expected to get an exception. It doesn't occur, but a.x
is initialized to zero.
How do I check that every field has been read?
Gson unfortunately does not provide this functionality out of the box at the moment, see the corresponding feature request. And it does not detect unknown fields either.
Maybe the answers to the question Gson optional and required fields are helpful. You could also try to write a generic TypeAdapterFactory
yourself which gets the fields of a class and checks if values for them are present in the JSON data, but such code might be difficult to maintain and would not integrate well with other Gson features, such as custom field naming or exclusion strategies.
For now it might be best to check if there any third-party extension libraries for Gson which offer this feature, or if other JSON libraries have better support for this.