Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON to Java enum

Tags:

java

json

android

I have the following enumeration in Java on Android and I would like to be able to deserialize an integer in an incoming JSON string/object into this Enum type. I have been getting hits on Jackson and GSON but nothing on the JSON.org package, which I am using.

Is there an easy way to do this or do I need to alter the JSON decoder? Thanks.

public enum ValueEnum {

    ONE(1),
    TWO(2),
    THREE(3);

    private int value;

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

    public int getValue() {
        return value;
    }   
}
like image 937
jim Avatar asked Oct 02 '12 14:10

jim


1 Answers

ValueEnum.values() will return you array of ValueEnum[] then you can iterate over array and check for Value

public static ValueEnum valueOf(int value) {
        ValueEnum[] valueEnums = ValueEnum.values();
        for (ValueEnum valueEnum : valueEnums) {
            if (valueEnum.getValue() == value)
            {
                return valueEnum;
            }
        }
        return DEFAULT;
    }
like image 84
Amit Deshpande Avatar answered Sep 25 '22 02:09

Amit Deshpande