Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize and deserialize enum with Gson [duplicate]

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

public enum Color {      RED, BLUE, YELLOW; } 
like image 756
user2183448 Avatar asked May 24 '13 16:05

user2183448


2 Answers

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;     }  } 
like image 152
Julio Rodrigues Avatar answered Sep 21 '22 01:09

Julio Rodrigues


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.

like image 38
MikO Avatar answered Sep 21 '22 01:09

MikO