Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abstractly deserialize different enum types with Jackson based on common field?

Problem:

I am deserializing enums with Jackson that don't match up with their name in the code, below is a sample of json.

{
    "thing1": {"foo": "cool-guy"},
    "thing2": {"foo": "loser-face"}
}

Here is the enum, I will explain the interface later.

enum Foo implements HasText {
    COOL_GUY("cool-guy"), LOSER_FACE("loser-face"), // etc...

    private String text;

    private Foo(String text) {
        this.text = text;
    }

    @Override
    public String getText() {
        return text;
    }
}

I know how to solve this issue for each enum individually by making a deserializer (below) and the annotation @JsonDeserialize(using = FooDeserializer .class) on the setter method for foo.

public class FooDeserializer extends JsonDeserializer<Enum<Foo>> {
    @Override
    public Foo deserialize(JsonParser p, DeserializationContext context) throws Exception {

      if (p.getCurrentToken().equals(JsonToken.VALUE_STRING)) {
        String jsonText = p.getText();
        Stream<Foo> stream = Arrays.asList(Foo.values()).stream();
        return stream.filter(a -> a.getText().equals(jsonText.toLowerCase())).findAny().get();
      }

      throw context.mappingException(Foo.class);
    }
}

Question:

Is there a way to do this abstractly? That's why I added the HasText interface to all my enums in hopes there was a way to do something like this:

public class EnumWithTextDeserializer<T extends Enum<T> & HasText> extends JsonDeserializer<T> {

    @Override
    public T deserialize(JsonParser p, DeserializationContext context) throws Exception {
        if (p.getCurrentToken().equals(JsonToken.VALUE_STRING)) {
          final String jsonText = p.getText();
          final Stream<T> stream = Arrays.asList(runtimeClass().getEnumConstants()).stream();
          return stream.filter(a -> a.getText().equals(jsonText.toLowerCase())).findAny().get();
        }
        throw context.mappingException(runtimeClass());
    }

    @SuppressWarnings("unchecked")
    private Class<T> runtimeClass() {
        ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
        return (Class<T>) superclass.getActualTypeArguments()[0];
    }
}

The compile won't let me annotate the setter method (@JsonDeserialize(using = EnumWithTextDeserializer.class)) with this class though because

Type mismatch: cannot convert from Class<EnumWithTextDeserializer> to Class<? extends JsonDeserializer<?>>".

Really, all I want to be able to do is deserialize these enums based on the getText() method.

like image 258
Captain Man Avatar asked Apr 18 '15 17:04

Captain Man


1 Answers

In order to deserialize, you can specify your String value using @JsonValue.

public enum FooEnum implements WithText {
    AWESOME("awesome-rad"),
    NARLY("totally-narly");

    private final String text;

    FooEnum(String text) {
        this.text = text;
    }

    @Override
    @JsonValue
    public String getText() {
        return text;
    }

}

Then executing this code to serialize/deserialize

    ImmutableMap<String, FooEnum> map = ImmutableMap.of("value", FooEnum.AWESOME, "value2", FooEnum.NARLY);
    final String value;
    try {
        value = objectMapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
        throw Throwables.propagate(e);
    }

    Map<String, FooEnum> read;
    try {
        read = objectMapper.readValue(value, new TypeReference<Map<String, FooEnum>>() {});
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

I get:

read = {LinkedHashMap@4627}  size = 2
  0 = {LinkedHashMap$Entry@4631} "value1" -> "AWESEOME"
  1 = {LinkedHashMap$Entry@4632} "value2" -> "NARLY"
like image 56
alexwen Avatar answered Oct 04 '22 07:10

alexwen