Search code examples
javastringspring-bootenumsannotations

How to convert String to Enum with an annotation in spring boot


I want to create an annotation that converts String to my Enum object. I have a DTO object that gets a String field named type as request body. Here I want to take that String and covert it to my Enum object with a custom annotation.

Enum object:

public enum Type {

    MOVIE_CAPABLE,
    SERIES_CAPABLE,
    MOVIE_SERIES_CAPABLE
}

DTO object:

@Data
public class ProviderRequest {

    @ConvertToEnum
    private Type type;

    // Other stuff
}

I know that it will work with uppercase String like MOVIE_CAPABLE without any kind of converting but I want to be able to send lowercase string too.

Thanks!


Solution

  • Yes this is possible, you can use @JsonDeserialize annotation on top of private Type type;

    Here is the full working implementation.

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class ProviderRequest implements Serializable {
    
        @JsonDeserialize(using = EnumTypeDeserializer.class)
        private Type type;
        // Other stuff
    }
    
    public class EnumTypeDeserializer extends JsonDeserializer<Type> {
    
        @Override
        public Type deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            final ObjectCodec objectCodec = jsonParser.getCodec();
            final JsonNode node = objectCodec.readTree(jsonParser);
            final String type = node.asText();
            return Type.valueOf(type.toUpperCase());
        }
    }