The Java Enum for REST/JSON API
The enum is defined by Java as,
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST)
The Java enum that you define is case-sensitive and can only be created from exactly matched string. If we define the Directions enum as,
Then, Directions.valueOf("NORTH") successfully creates Directions.NORTH as expected. But, Directions.valueOf("North") or Directions.valueOf("north") throws IllegalArgumentException.
The case sensitive requirement of Java enum might be a restrictive dealing with external systems. It would be great, if we are tolerable to our clients by not strictly enforcing the case and at the same time setting the standards on how the clients receive the data with only a little Java code. This blog explains that simple, yet elegant solution to deal with enums especially in JSON/REST API applications.
The following function can create a java enum from case insensitive strings. If in case of an invalid string, this function emits all possible values of that enum as a feed back to the user to recover from the error.
Now, getEnumFromString(Directions.class, "North") will return Directions.NORTH.
But, getEnumFromString(Directions.class, "North-East") will throw the following exception indicating all the possible values of the enum...
Exception in thread "main" java.lang.IllegalArgumentException: North-East is invalid value. Supported values are NORTH, SOUTH, EAST, WEST
Armed with such a function, a Java enum can be nicely integrated to deal with JSON/XML with a Jackson kind of JSON processor. Moreover, it seamlessly integrates for JSR-303 Validations. This function should be part of any organization's common library.
Now let us make our Directions enum to work with JSON. If the widely used JACKSON is your serializer/deserializer , then the Directions enum will become as
The @JsonCreator indicates Jackson on how to create the Directions enum, and our case-insensitive getEnumFromString function creates the desired enum. A simple and elegant case-insensitive enum is ready.
If the specifications define the Directions as "north, south, east, west" in stead of all capitals, then we require to add @JsonValue as indicated below.
So with such a generic getEnumFromString utility function, we can achieve...
- enum creation from case insensitive string
- Validation
- Implicit support of JSR-303 Bean Validation
- Serialization/De serialization control to establish and comply standards.
You can refer/download the java demo code at enum demo gist.
thanks for sharing, just what I was looking for.
Great article and exactly what I needed! I always felt bad when I had to break the code conventions to achieve the lower case REST Enums.