Disable JSON using GSON for Enum

My goal is to parse a JSON file or part of it into an Enum class in Java. I can do this easily, but for debugging reasons, I would also like to enable the default value.

public enum MyEnum {
    @SerializedName("texts")
    TEXTS,
    @SerializedName("buttons")
    BUTTONS,
    @SerializedName("inputs")
    INPUTS,
    DEFAULT
}

So, if I try to parse this JSON (using the wrapper class):

{enum: "buttons"}

I would get MyEnum.BUTTONS, but if I try to parse:

{enum: "divider"}

I would still like to know the meaning. I would like to map all values ​​(e.g. "separator", "string", "color", ...) to DEFAULT(supporting the string being mapped to the value DEFAULT). Is it possible to save the value "separator" in the property MyEnum.DEFAULT?

+4
source share
1 answer

JsonDeserializer GsonBuilder.registerTypeAdapter. :

public enum MyEnum {
    TEXTS ("texts"),
    BUTTONS("buttons"),
    INPUTS("inputs"),
    DEFAULT(null);

    private String text;

    private MyEnum (String text) {
        this.text = text;
    }

    public String getValue () {
        return text;
    }

    public static MyEnum mapFrom (String serialized) {
        if (serialized == null) {
            DEFAULT.text = null;
            return DEFAULT;
        }
        for (MyEnum inst : MyEnum.values()) {
            if (serialized.equals(inst.getValue())) {
                return inst;
            }
        }
        DEFAULT.text = serialized;
        return DEFAULT;
    }
}

( ) mapFrom . , DEFAULT , , , , , , , , .

, , , , . , . , - .

- , enum, .

0

All Articles