serialize and deserialize enum with Gson

user2183448 picture user2183448 · May 24, 2013 · Viewed 57.5k times · Source

How can i serialize and deserialize a simple enum like this with gson 2.2.4 ?

public enum Color {

    RED, BLUE, YELLOW;
}

Answer

Julio Rodrigues picture Julio Rodrigues · Jul 8, 2014

You can try this.

import com.google.gson.annotations.SerializedName;

public enum Color {

    @SerializedName("0")
    RED (0), 

    @SerializedName("1")
    BLUE (1),

    @SerializedName("2")
    YELLOW (2);

    private final int value;
    public int getValue() {
        return value;
    }

    private Color(int value) {
        this.value = value;
    }

}