Jackson deserialize "simple type" to enum

Viewed 292

I have a common class

public CommonClass {
    private Enum<?> field1;
    private String field2;
    private String field3;
    private Map<? extends Enum<?>, Map<String, Object>> map;
    // constructor, getters setters
}

And two enums

public enum A {
  FIELD,
  VALUE
}
public enum B {
   ENUM1,
   ENUM1
}

And json to parse in it class

{
  "field1": "FIELD",
  "field2": "field2",
  "field3": "field2",
  "map": {
    "ENUM1": {
           // some inner data
      },
    "ENUM2":{
          // some inner data
    }
   }
}

When I try to parse this JSON to an object I got an exception

java.lang.IllegalArgumentException: No enum constants for class java.lang.Enum

This exception occurs when Jackson tried to deserialize "ENUM1" which is a ? extends Enum<?> to B
When I debug it, Jackson thought that this property is simple type.
Is any suggestion why it doesn't work?

1 Answers

I think you cannot deserialize even this simplified one by default:

public class CommonClass {
    private Enum<?> field1;     
}

I is because no Enum nor enum has public no args constructor. To serialize beforementioned is easy. But to deserialize you need to know which enum and which value. So if you had:

public class CommonClass {
    private A field1;       
}

It would work because Jackson sees the enum is of type A and - I guess - makes it like:

A.valueOf("FIELD");

And as you see here A is static. Enums are static and also their values are final.

If you want to deserialize arbitrary generic enum value Enum<?> you need to have custom deserializer that determines the enum type and together with value and gets instance of enum like above. And you might also need a custom serializer that serializes also the type for custom deserializer to read.

Related