0

I am deserializing a field from JSON to my custom enum. The requirement that I have is that if the JSON field string is not the part of my enum, it should deserialize it to the DEFAULT enum value.

Here is my enum.

public enum Status {

    Y("Y"),

    N("N"),

    U("U"),

    A("A"),

    C("C"),

    R("R"),

    UNKNOWN(/* any other string value */) // this is what i need


    private final String textualValue;


    Status(String textualValue) {
        this.textualValue = Objects.requireNonNull(textualValue);
    }

    @Override
    public String toString() {
        return textualValue;
    }

So, basically if a JSON contains something like {"status":"X"}, I want that to deserialized into Status.UNKNOWN, just as now ie. {"status":"A"} deserializes into Status.A.

I am doing my mappings with ObjectMapper.

protected static final ObjectMapper jsonMapper =
        new ObjectMapper()
        .registerModule(new Jdk8Module())
        .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
        .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);

Is something like that possible?

wesleyy
  • 2,575
  • 9
  • 34
  • 54

0 Answers0