Suppose I am using Google’s Gson library to parse JSON into Java data structures.
Is there an easy way to throw an exception if there is a Java field that has no corresponding JSON? That is, I wish to require the JSON to have all the fields in the Java structure.
Gson doesn’t have a JSON schema validation feature to specify that a particular element must be present, and it doesn’t have a way to specify that a Java member must be populated. It might be nice to have such a feature available, such as with an
@Requiredannotation. Head on over to the Gson Issues List and put in an enhancement request.With Gson, you could enforce that specified JSON elements are present with a custom deserializer.
A preferable approach might be to use an API that provides JSON Schema validation. Jackson has at least a rudimentary implementation available. JSON Tools looks to have a more mature one.
Here’s an example with Jackson.