I'm trying to map this JSON :
{"ref":"code","type":"desc"}
With those JAX-RS classes :
public class Sorting {
public String ref;
public SortingType type;
}
@XmlType
@XmlEnum
public enum SortingType {
@XmlEnumValue("asc")
ASCENDING,
@XmlEnumValue("desc")
DESCENDING;
}
With this I have that error (I'm using JBoss EAP 6.2):
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.mycompany.myproject.SortingType from String value 'desc': value not one of declared Enum instance names
at [Source: org.apache.catalina.connector.CoyoteInputStream@76e7449; line: 1, column: 47] (through reference chain: com.mycompany.myproject.Sorting["type"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
By looking at the documentation, I've also tried that definition without any success:
@XmlType
@XmlEnum
public enum SortingType {
@XmlEnumValue("asc")
ASCENDING("asc"),
@XmlEnumValue("desc")
DESCENDING("desc");
private String code;
SortingType(String code) {
this.code = code;
}
}
I used that ugly code waiting a better answer:
@XmlEnum
public enum SortingType {
@XmlEnumValue("asc")
ASCENDING,
@XmlEnumValue("desc")
DESCENDING;
private static Map<String, SortingType> sortingTypeByValue = new HashMap<>();
private static Map<SortingType, String> valueBySortingType = new HashMap<>();
static {
SortingType[] enumConstants = SortingType.class.getEnumConstants();
for (SortingType sortingType : enumConstants) {
try {
String value = SortingType.class.getField(sortingType.name()).getAnnotation(XmlEnumValue.class).value();
sortingTypeByValue.put(value, sortingType);
valueBySortingType.put(sortingType, value);
} catch (NoSuchFieldException e) {
throw new IllegalStateException(e);
}
}
}
@JsonCreator
public static SortingType create(String value) {
return sortingTypeByValue.get(value);
}
@JsonValue
public String getValue() {
return valueBySortingType.get(this);
}
}