javajsonb-apiyasson

Ignore enum case with JSON-B / Yasson


Using JSON-B / Yasson is there any way to ignore case of enums when deserializing?

public class MyObject{
  MyEnum condition;
  //getters and setters
} 
public enum MyEnum{
 NEW, OLD, REFURBISHED;
}

part of incoming JSON: "condition" : "new" The problem is that the incoming JSON uses the enums in lowercase.


Solution

  • I don't thing this should be available out of the box. Because you technically can have both old and OLD as valid values of your enum living together, allowing for out-of-the-box uppercase conversion can break roundtrip equivalence. Think of serializing a MyEnum.old value to end up with a MyEnum.OLD value on deserialization.

    You can however force such a behavior by using an adapter.

    public static class MyAdapter implements JsonbAdapter<MyEnum, String> {
    
        @Override
        public String adaptToJson(MyEnum value) {
            return value.name();
        }
    
        @Override
        public MyEnum adaptFromJson(String s) {
            return MyEnum.valueOf(s.toUpperCase());
        }
    }
    

    Next, annotate the enum with @JsonbTypeAdapter.

    @JsonbTypeAdapter(MyAdapter.class)
    public enum MyEnum {
        NEW,
        OLD,
        REFURBISHED;
    }
    

    Alternatively, you create your Jsonb provider as follows.

    Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withAdapters(new MyAdapter()));