Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Http Java Client parsing to enum

Tags:

java

json

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?

like image 331
yincrash Avatar asked Mar 01 '13 20:03

yincrash


1 Answers

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?

like image 122
Lital Kolog Avatar answered Oct 09 '22 07:10

Lital Kolog