serialize and deserialize enum with Gson

JavaSerializationEnumsDeserializationGson

Java Problem Overview


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

public enum Color {

	RED, BLUE, YELLOW;
}

Java Solutions


Solution 1 - Java

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

}

Solution 2 - Java

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.

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2183448View Question on Stackoverflow
Solution 1 - JavaJulio RodriguesView Answer on Stackoverflow
Solution 2 - JavaMikOView Answer on Stackoverflow
Solution 3 - JavaBart BurgView Answer on Stackoverflow