0

Here's my situation,

I have a class with Enum type fields. I want to execute annotated validation for enum types, similar to annotations for strings, example: @Size, @NotNull etc.

Problem is, json deserializer fails on enum type before validation occurs.

public class myClass {
    @JsonProperty
    //@SomeCustomValidator -- ??
    private EnumType enumValue;
}

public enum EnumType {
    A,
    B,
    C
}

Few things:

  1. I do not want to change the data type to String.
  2. Tried steps in following threads, didn't fix my problem.

    Tried this link, but get an error in deserialization before validation hits

    Tried this link, but it works only when data Type is String

coder
  • 8,346
  • 16
  • 39
  • 53

1 Answers1

0

Validation works after the type of the argument is resolved. So I don't see a way how to use String validating annotations on enums. As workaround you can use @JsonCreator and do some validation before object creation.

public enum EnumType {
    A,
    B,
    C;

    @JsonCreator
    public static EnumType from(String s) {
        // add your logic here, for example
        /*
        if (Stream.of(values()).map(Enum::name).noneMatch(name -> name.equals(s))) {
            throw new MyServiceException("Bad value " + s);
        }
        */
        return valueOf(s);
    }
}
  • Thanks. This is a good approach.., but no logic works unless I return null, in which case no exception occurs and a null value is assigned to field. Do you have a working solution with this approach? – Prabhdeep Gill May 06 '18 at 23:19
  • You can throw an Exception or return null or any instance of your enum. I thought your goal was to throw custom Exception based on String value from json. If it wasn't I don't know what the goal you are trying to achieve. – Bogdan Lukiyanchuk May 07 '18 at 06:12