使枚举不区分大小写

noe*_*oel 4 java

我正在构建一个 Spring Boot REST API。它有一个 POST 请求,将大对象保存到 Mongo 数据库。我试图使用枚举来控制数据存储方式的一致性。例如,这是我的对象的一部分:

public class Person{
   private String firstName;
   private String lastName:
   private Phone phone;
}
Run Code Online (Sandbox Code Playgroud)
public class Phone {
    private String phoneNumber;
    private String extension;
    private PhoneType phoneType;
}
Run Code Online (Sandbox Code Playgroud)
public enum PhoneType {
    HOME("HOME"),
    WORK("WORK"),
    MOBILE("MOBILE");

    @JsonProperty
    private String phoneType;

    PhoneType(String phoneType) {
        this.phoneType = phoneType.toUpperCase();
    }

    public String getPhoneType() {
        return this.phoneType;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题:当我传入枚举的大写版本以外的值(例如“mobile”或“Mobile”)时,出现以下错误:

JSON parse error: Cannot deserialize value of type `.......PhoneType` from String "mobile": not one of the values accepted for Enum class: [HOME, WORK, MOBILE]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `......PhoneType` from String "mobile": not one of the values accepted for Enum class: [HOME, WORK, MOBILE]
Run Code Online (Sandbox Code Playgroud)

我觉得应该有一种相对简单的方法来获取传递给 API 的内容,将其转换为大写,与枚举进行比较,如果匹配,则存储/返回枚举。不幸的是,我还没有找到一个有效的模式,因此这个问题。预先感谢您的帮助!

noe*_*oel 5

Berto99 的评论让我得到了正确的答案:

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

public enum PhoneType {
    HOME("HOME"),
    WORK("WORK"),
    MOBILE("MOBILE");

    private String phoneType;

    PhoneType(String phoneType){
        this.phoneType = phoneType;
    }

    @JsonCreator
    public static PhoneType fromString(String phoneType) {
        return phoneType == null
            ? null
            : PhoneType.valueOf(phoneType.toUpperCase());
    }

    @JsonValue
    public String getPhoneType() {
        return this.phoneType.toUpperCase();
    }
}
Run Code Online (Sandbox Code Playgroud)