So, I'm aware that you can parse json values into enums using @Value
annotation, but what is the behavior if the value in the json does not match any values annotated with @Value
. For example, say an api decides to add a new type that your client doesn't know about. Does its value get set to null, or is there an exception? Is there a way to set an enum value as the default catch all value?
1 Answer
According to this Google groups post, you will get NullPointerException
.
Edit
Referenced content:
I have an object called Job with a enum field statusCode that holds an API. That enum is correctly annotated with @Value, so long as the enum handles all possible values that might come back in the status_code field, json parsing works just fine.
public static class Job { @Key("status_code") public JobStatus statusCode; } public enum JobStatus { @Value("starting") STARTING }
However, if an unknown value comes back in that field, then I get a
NullPointerException: java.lang.NullPointerException at com.google.api.client.util.Data.parsePrimitiveValue(Data.java:445) at com.google.api.client.json.JsonParser.parseValue(JsonParser.java:795) at com.google.api.client.json.JsonParser.parse(JsonParser.java:438) at com.google.api.client.json.JsonParser.parseValue(JsonParser.java:745) at com.google.api.client.json.JsonParser.parse(JsonParser.java:358) at com.google.api.client.json.JsonParser.parse(JsonParser.java:331) at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:87) at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81) at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:459)
I would like this code to be robust such that if an unknown value comes back it will be treated as null rather than throwing an exception and not returning the Job object. Is there any way to do this?
-
1Please include more detail into the answer. If the linked page gets removed or becomes inaccessible, this link-only answer will become irrelevant.– SufianCommented Apr 27, 2015 at 6:39
NOT_A_VALUE
is used as a catch-all. What happens if you have one of those defined?