Using Enums while parsing JSON with GSON

Sachin Kulkarni picture Sachin Kulkarni · Nov 21, 2011 · Viewed 91k times · Source

This is related to a previous question that I asked here earlier

JSON parsing using Gson

I am trying to parse the same JSON, but now I have changed my classes a little bit.

{
    "lower": 20,
    "upper": 40,
    "delimiter": " ",
    "scope": ["${title}"]
}

My class now looks like:

public class TruncateElement {

   private int lower;
   private int upper;
   private String delimiter;
   private List<AttributeScope> scope;

   // getters and setters
}


public enum AttributeScope {

    TITLE("${title}"),
    DESCRIPTION("${description}"),

    private String scope;

    AttributeScope(String scope) {
        this.scope = scope;
    }

    public String getScope() {
        return this.scope;
    }
}

This code throws an exception,

com.google.gson.JsonParseException: The JsonDeserializer EnumTypeAdapter failed to deserialized json object "${title}" given the type class com.amazon.seo.attribute.template.parse.data.AttributeScope
at 

The exception is understandable, because as per the solution to my previous question, GSON is expecting the Enum objects to be actually be created as

${title}("${title}"),
${description}("${description}");

But since this is syntactically impossible, what are the recommended solutions, workarounds?

Answer

validcat picture validcat · Sep 17, 2013

I want to expand a bit NAZIK/user2724653 answer (for my case). Here is a Java code:

public class Item {
    @SerializedName("status")
    private Status currentState = null;

    // other fields, getters, setters, constructor and other code...

    public enum Status {
        @SerializedName("0")
        BUY,
        @SerializedName("1")
        DOWNLOAD,
        @SerializedName("2")
        DOWNLOADING,
        @SerializedName("3")
        OPEN
     }
}

in the json file you have just a field "status": "N",, where N=0,1,2,3 - depend on the Status values. So that's all, GSON works fine with the values for the nested enum class. In my case i've parsed a list of Items from json array:

List<Item> items = new Gson().<List<Item>>fromJson(json,
                                          new TypeToken<List<Item>>(){}.getType());