3

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!

noel
  • 383
  • 4
  • 18
  • 2
    maybe `spring.jackson.mapper.ACCEPT_CASE_INSENSITIVE_ENUMS = true`? – Alberto Sinigaglia May 28 '21 at 14:58
  • Thank you. This comment led me to this post, which contains a variety of ways to solve this issue: https://stackoverflow.com/questions/24157817/jackson-databind-enum-case-insensitive/44217670 – noel May 28 '21 at 16:15

1 Answers1

4

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();
    }
}
noel
  • 383
  • 4
  • 18