首页 > 解决方案 > 带有枚举的请求的 ConversionFailedException

问题描述

在我的 spring-boot 应用程序中,我有一个带有“ReadOrderRequest”的端点在请求模型中,我有一个枚举字段 SourceSystem:

@ApiParam(value = "Source crm system for the order")
private SourceSystem sourceSystem;

这就是我的 SourceSystem 枚举的样子:

package qwerty.resources.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

public enum SourceSystem {
    ABC("abc"),
    DEF("def"),
    GHI("ghi");

    private final String value;

    SourceSystem(String value) {
        this.value = value;
    }
    
    @JsonCreator
    public static SourceSystem fromValue(String value) {
        for (SourceSystem system : SourceSystem.values()) {
            if (system.toString().equalsIgnoreCase(value)) {
                return system;
            }
        }
        return null;
    }

    @Override
    @JsonValue
    public String toString() {
        return value;
    }
}

招摇是这样生成的:

          {
            "name": "sourceSystem",
            "in": "query",
            "description": "Source crm system for the order",
            "required": false,
            "type": "string",
            "enum": [
              "abc",
              "def",
              "ghi"
            ]
          },

但是,在使用端点时,我得到以下异常。

"readOrdersRequest: Failed to convert property value of type 'java.lang.String' to required type 'qwerty.resources.model.SourceSystem' for property 'sourceSystem'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiParam qwerty.resources.model.SourceSystem] for value 'abc'; nested exception is java.lang.IllegalArgumentException: No enum constant qwerty.resources.model.SourceSystem.abc"

所以看起来问题是值(小写)被发送到端点,然后找不到匹配项,因为实际的枚举是大写的。但是我认为“fromValue”方法应该可以解决这个问题,但不幸的是事实并非如此。

你对我如何解决这个问题有什么建议吗?

第一次发帖,如果需要修改请告诉我:)

标签: javaspringenums

解决方案


推荐阅读