有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Jackson:反序列化枚举

我正在REST API中使用Jackson+Spring。其中一个API调用的JSON如下所示:

{
    "status": "Suspended"
}

其中“status”的值映射到Java枚举,如下所示:

public enum FeatureStatus {
    Activated(0),
    Inactivated(1),
    Suspended(2),
    Deleted(3);

    private FeatureStatus(int id) {
        this.id = id;
    }

    private int id;

    public int getId() {
        return id;
    }

    public FeatureStatus valueOf(int id) {
        switch(id) {
            case 1: return Inactivated;
            case 2: return Suspended;
            case 3: return Deleted;
            default: return Activated;
        }
    }

    @JsonCreator
    public static FeatureStatus fromValue(String status) {
        if(status != null) {
            for(FeatureStatus featureStatus : FeatureStatus.values()) {
                if(featureStatus.toString().equals(status)) {
                    return featureStatus;
                }
            }

            throw new IllegalArgumentException(status + " is an invalid value.");
        }

        throw new IllegalArgumentException("A value was not provided.");
    }
}

但是,会引发此异常:java.lang.IllegalArgumentException: { is an invalid value.看起来它根本没有反序列化JSON。我的控制器方法有以下定义:

public @ResponseBody void updateFeatureStatusById(@PathVariable long featureId, @RequestBody FeatureStatus updated) {

任何其他控制器都会按照预期使用此格式自动反序列化JSON。如何将这个JSON反序列化到我的枚举中


共 (1) 个答案

  1. # 1 楼答案

    传递对象的是准确的JSON吗?枚举,但JSON字符串或数字除外,而不是对象。 如果你需要给出一个对象,你应该把它映射到如下位置:

    public class EnumWrapper {
      public FeatureStatus status;
    }
    

    它会起作用的