8

So, I'm aware that you can parse json values into enums using @Valueannotation, 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?

2
  • Why not use something like code.google.com/p/json-simple? It's all already there. Or if you like to save and read back objects you could use code.google.com/p/google-gson no need to write your own parser? Commented Apr 27, 2015 at 6:38
  • Their javadoc is pretty barebones, but it seems to suggest that an enum value named NOT_A_VALUE is used as a catch-all. What happens if you have one of those defined? Commented Apr 29, 2015 at 5:09

1 Answer 1

2

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?

1
  • 1
    Please include more detail into the answer. If the linked page gets removed or becomes inaccessible, this link-only answer will become irrelevant.
    – Sufian
    Commented Apr 27, 2015 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.