无法处理弹簧数据中的eNum

时间:2016-03-22 20:51:07

标签: enums spring-data-mongodb

我使用枚举作为数据模型的一部分。当我反序列化我的输入json时,我的数据模型中的枚举不会被填充。

你能告诉我吗?

work = chain(taskA, taskB) return work() taskB: creates the following workflow: work = group(**group(taskC, taskD)** | taskE), **group(taskC, taskD**) | taskE)) | taskF return work()

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

}

我的inputJson是

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

反序列化

{ "accessType":"public" }

1 个答案:

答案 0 :(得分:1)

您应该在所有枚举字段中添加注释“SerializedName”。注释的文档位于:https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

你的枚举看起来像

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

另请注意,您无法反序列化枚举,您应该使用包装器对象,如:

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