Ram Viswanathan
Ram Viswanathan

Reputation: 201

Unable to handle eNum in spring data

I am using an enum as part of my data model. When I deserialize my input json, the enum in my data model does not get populated.

Can you please advise?

public enum AccessTypeEnum {

PUBLIC(1, "public"),
PRIVATE(2, "private"),

private int code;
private String accessType;

private AccessTypeEnum(int code, String accessType) {
    this.code = code;
    this.accessType = accessType;
}

public String getAccessType() {
    return accessType;
}

public int getCode() {
    return code;
}

}

My inputJson is

{ "accessType":"public" }

To deserialize

AccessTypeEnum e = gson.fromJson(inputJson, AccessTypeEnum.class);

Upvotes: 1

Views: 59

Answers (1)

Igor Bljahhin
Igor Bljahhin

Reputation: 987

You should add annotations "SerializedName" to all enum fields. The documentation for the annotation is here: https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

Your enum will look like

import com.google.gson.annotations.SerializedName;

public enum AccessTypeEnum {    
    @SerializedName("public") PUBLIC(1, "public"),
    @SerializedName("private") PRIVATE(2, "private"),

    private int code;
    private String accessType;

    private AccessTypeEnum(int code, String accessType) {
        this.code = code;
        this.accessType = accessType;
    }

    public String getAccessType() { return accessType; }
    public int getCode() { return code; }
}

Also please note, that you can't deserialize enum, you should use wrapper object, like:

class MyObj {
    AccessTypeEnum accessType;
}

public static final void main(String args[]) {
    MyObj obj = new Gson().fromJson("{ \"accessType\": \"public\" }", MyObj.class);
    System.out.println("" + obj.accessType);
}

Upvotes: 1

Related Questions