Convert annotation string to enum value with Jackson

Viewed 153

I have an enum with @JsonProperty annotated:

public enum Type {
    @JsonProperty("Files")
    File,
    @JsonProperty("Folders")
    Folder,
}

I know I can deserialize a JSON string ({"fieldName":"Files"}) to get an object. But is there any way to convert the string annotated in @JsonProperty to enum value with Jackson like:

String s = "Files"
Type t = jackson.valueOf(s); // Type.File

Or can I achieve this:

Type t = Type.File;
String s = jackson.toString(t); // "Files"

I believe that a private String value can resolve this, but the code would have duplicated constants (too many "Files" and "Folders"). I wonder if Jackson or Gson has solution to achieve this.

2 Answers

It should just work with help of ObjectMapper

Type t = new ObjectMapper().readValue("\"Files\"", Type.class);
System.out.println(Type.File.equals(t)); //"true"

Please note that the String needs to be a valid JSON string, so it must contain the double quotes. The string content cannot be Files, but rather has to be "Files"

The other direction:

Type t = Type.File;
new ObjectMapper().writeValue(System.out, t); // "Files"

If I am understanding you correctly, then perhaps this is what you are looking for:

String annotationValueAsSTring = Type.class.getField(Type.File.name()) 
                         .getAnnotation(JsonProperty.class).value();

-- Edited --

To retrieve the Enum value from the @JsonProperty String value, then you will need to create a helper method:

public static <T extends Enum<T>> Optional<T> getEnumValueFromJsonProperty(Class<T> enumClass,
                                                                           String jsonPropertyValue) {
    Field[] fields = enumClass.getFields();
    return Arrays.stream(fields).filter(field -> field.getAnnotation(JsonProperty.class).value().equals(jsonPropertyValue)).map(field -> Enum.valueOf(enumClass, field.getName())).findFirst();
}
Related