serialize and deserialize enum with Gson [duplicate]

寵の児 提交于 2019-12-18 10:15:12

问题


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

public enum Color {

    RED, BLUE, YELLOW;
}

回答1:


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.




回答2:


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

}



回答3:


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


来源:https://stackoverflow.com/questions/16740078/serialize-and-deserialize-enum-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!