'Jackson generic enum deserialization

I have a generic class that has a list field as following:

//-- Parent class
public abstract class Attribute<T> {
   protected String name;
   protected List<T> allowableValues = new ArrayList<>();

   //-- Other kinds of stuff
}

//-- Child
public class EnumAttribute extends Attribute<Enum> {
  //-- Other fields and methods
}

In class EnumAttribute generic type is Enum which is a java data type and is the parent of an enum that any developer can declare in source, like public enum Color{RED, BLUE}.

Note: All enums implicitly extend java.lang.Enum. Reference

This means any enum that is an EnumAttribute and the allowableValues field in super class fills with related enums, for example List<Color> allowableValues = new ArrayList<>()

I'm using Jackson to serialize/deserialize objects.

So the question:

When I serialize an object of EnumAttribute, Jackson works properly, but on the deserializing time, it can not detect which enum should pick.

Let me follow up with an example:

Gendar enum:

public enum Gendar{
   MALE, FEMALE
}

Color enum:

public enum Color{
   RED, BLUE, GREEN
}

We can initiate an object of EnumAttribute from both of the above enums.

And this is the EnumAttribute object that has been serialized to JSON:

{
   "name": "color",
   "allowableValues": ["BLUE", "GREEN"]
}

When I want to deserialize the above object, Jackson rise an error which says: can not find a constructor in Enum, while the concrete enum is `Color.

Note: I know one way to solve the problem is by defining a custom deserializer for Enum.

But I'd like to know are there any other ways to solve the problem?

Or Is there any best practice for this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source