Skip to content

Instantly share code, notes, and snippets.

@rdara
Created March 6, 2015 00:21
Show Gist options
  • Save rdara/ed90dfb6b36db3d5db16 to your computer and use it in GitHub Desktop.
Save rdara/ed90dfb6b36db3d5db16 to your computer and use it in GitHub Desktop.
The Java Enum for REST/JSON API
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* @author Ramesh Dara
*/
public class enumDemo {
public static void main(String[] args) {
getEnumFromString(Directions.class, "North");
getEnumFromString(Directions.class, "North-East");
}
public static <T extends Enum<T>> T getEnumFromString(Class<T> enumClass, String value) {
if (enumClass == null) {
throw new IllegalArgumentException("EnumClass value can't be null.");
}
for (Enum<?> enumValue : enumClass.getEnumConstants()) {
if (enumValue.toString().equalsIgnoreCase(value)) {
return (T) enumValue;
}
}
//Construct an error message that indicates all possible values for the enum.
StringBuilder errorMessage = new StringBuilder();
boolean bFirstTime = true;
for (Enum<?> enumValue : enumClass.getEnumConstants()) {
errorMessage.append(bFirstTime ? "" : ", ").append(enumValue);
bFirstTime = false;
}
throw new IllegalArgumentException(value + " is invalid value. Supported values are " + errorMessage);
}
public enum Directions {
NORTH,
SOUTH,
EAST,
WEST;
@JsonCreator
public static Directions fromValue(String value) {
return getEnumFromString(Directions.class, value);
}
@JsonValue
public String toJson() {
return name().toLowerCase();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment