javaenumsjson-deserializationjackson-databindjson-serialization

Jackson Databind Deserializtion of Generic Enum


I am trying to properly save/load data containing a generic enum. Currently the object contains a java.lang.Class object (clazz) that get serialized into the field "enumclass". The "al" field contains the value of the enum. My goal is to create a custom Jackson deserializer that uses the "val" field and the "enumclass" field to then run Enum.valueOf() to create an instance of the Enum.

However, when I run the deserializer, it throws a JsonMappingException and says Cannot construct instance of 'java.lang.Class', problem: me.ExampleProject.Enums$RevealType$1

I can't seem to get past this one issue and am not sure how to proceed. Any help would be appreciated.

Example JSON:

"revealType": {
    "type": "enumspec",
    "id": "Reveal Type",
    "val": "SKIRT",
    "enumclass": "me.ExampleProject.Enums.RevealType",
    "ro": false,
    "sec": "Miscellaneous"
}

Deserialization Code:

Class clazz = MAP.convertValue(jsonNode.get("enumclass"), new TypeReference<Class<? extends Enum<?>>>() {});
Enum<?> value = Enum.valueOf(clazz, jsonNode.get("val").asText());

Solution

  • Jorn's comment

    Read the enumclass as a String, then use Class.forName

    Is what worked for me. The issue with the ClassNotFoundException was due to me using PF4J to load plugins. I had to register a list of all the plugin classloaders and use the method Class.forName(name, true, pluginClassLoader) to pass the plugin classloaders in manually to find the class.