77

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

public enum Color {

    RED, BLUE, YELLOW;
}
MikO
  • 18,243
  • 12
  • 77
  • 109
user2183448
  • 783
  • 1
  • 5
  • 7

3 Answers3

209

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;
    }

}
Julio Rodrigues
  • 3,373
  • 3
  • 24
  • 33
  • 2
    Note: this does not work with older versions of GSON. It works with version 2.1 and greater. – Kai Sternad Sep 24 '14 at 11:21
  • 7
    He asked for version 2.2.4, so yes – Bart Burg Dec 12 '14 at 16:11
  • 1
    This is a really great approach. I use it often, and I think that in newer versions of GSON, users should lean toward using this approach because it's concise and doesn't require complex custom serialization/deserialization code. – jwir3 Jan 23 '15 at 23:50
  • 7
    How to desalinize an unknown value of enum to `Unknown`? For example the above enum `Color` should have an `Unknown` field which represent value which is none of `0`, `1` or `2`. – Writwick Mar 29 '15 at 13:12
  • Will this work both if I choose to pass strings ("0","1"..) and if I pass numbers? (0,1,2..)? – user1386966 May 09 '16 at 09:01
  • This blog post helped me: Simple deserialization of Java enums using Google GSON annotations http://blog.jensdriller.com/simple-deserialization-of-java-enums-using-google-gson-annotations/ – Guy West Aug 11 '16 at 11:16
  • 1
    I have a restful web service that handles enum value (1, 2) instead of name when communicating, so the service is unable to parse the string value ("COLOR") in the request. The response object obtained from service is deserialized just OK with the numeric value. So this approach helped a lot. – YeinCM-Qva Aug 16 '18 at 19:59
  • this works in a debug build but not with a release build apk. It crashes saying: "java.lang.NoSuchFieldException" [YOUR_ENUM_NAME_HERE]. Any ideas? – Mike6679 Sep 19 '18 at 16:47
  • Found my issue. My proguard needed to keep my enum classes. See here: https://stackoverflow.com/questions/15543607/assertionerror-in-gson-enumtypeadapter-when-using-proguard-obfuscation – Mike6679 Sep 19 '18 at 17:39
  • 1
    This produces string values and not integers. – Johann Sep 04 '20 at 10:13
  • What if they API could send empty and/or null value too? How can we handle that? is it correct: `@SerializedName("") UNKNOWN("")`? – Dr.jacky Nov 02 '20 at 17:21
31

According to Gson API documentation, Gson provides default serialization/deserialization of Enum, so basically it should be serialized and deserialized using the standard toJson and fromJson methods, as with any other type.

helvete
  • 2,455
  • 13
  • 33
  • 37
MikO
  • 18,243
  • 12
  • 77
  • 109
  • 12
    by default, Gson serializes and deserializes by using the name of the enum instead of the ordinal value. Is there a way to set up one serializer and deserializer to handle all Enums by their ordinal values? – Churro Oct 22 '13 at 21:17
  • 15
    You can add annotation `@SerializedName` for enum. – ViliusK Apr 30 '14 at 16:09
  • 13
    @ViliusK that will make my enum to serialize as a String.valueOf(ordinal), is there a similar annotation or way to make my serialized enum an int? e.g. "color" : 1 is what I want, not "color" : "1". (mind the double quotations around 1) – Behnam Jul 06 '15 at 13:27
  • 17
    the link is dead. – user239558 Apr 04 '17 at 09:33
  • 1
    @SerializedName produces a string and not an integer. – Johann Sep 04 '20 at 10:12
1

This works fine as well, don't know from which version of GSON though:

public enum OrderLineTimeRegistrationStatus {
    None(0), Started(1), Paused(2);

    private int value;

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

    public int getValue()
    {
        return(value);
    }
}
Bart Burg
  • 4,786
  • 7
  • 52
  • 87
  • 5
    I am afraid, it does not work. Using Gson 2.8.0. How it could work anyway? Gson is smart, but not that smart. – wst Nov 14 '16 at 08:22