Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Enums case insensitive [duplicate]

Tags:

java

I am building a Spring Boot REST API. It has a POST request that saves a large object to a Mongo Database. I am attempting to use Enums to control the consistency of how the data is stored. For example, this is a portion of my object:

public class Person{
   private String firstName;
   private String lastName:
   private Phone phone;
}
public class Phone {
    private String phoneNumber;
    private String extension;
    private PhoneType phoneType;
}
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;
    }
}

My issue: When I pass in a value other than the capitalized version of my enum (such as "mobile" or "Mobile"), I get the following error:

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]

I feel like there should be a relatively easy way to take what is passed into the API, convert it to uppercase, compare it to the enum, and if it matches, store/return the enum. Unfortunately, I have yet to find a good pattern that'll work, hence this question. Thank you in advance for your assistance!

like image 260
noel Avatar asked Oct 30 '25 17:10

noel


1 Answers

Berto99's comment led me to the correct answer:

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();
    }
}
like image 129
noel Avatar answered Nov 02 '25 06:11

noel