для меня я создал интерфейс, который shuold будет реализован любым перечислением, которое мне нужно будет использовать в Json, этот интерфейс заставляет перечисление знать собственное перечисление из значения, а также оно должно возвращать значение. так что каждый enum.CONSTANT отображается на значение любого типа (погода число или строка)
поэтому, когда я хочу поместить это перечисление в объект Json, я прошу enum.CONSTANT дать мне это значение , и когда у меня есть это значение (от Json), я могу запросить у перечисления, чтобы дать мне правильное перечисление.КОНСТАНТА, сопоставленные с этим значением
интерфейс выглядит следующим образом (вы можете скопировать его, как он есть):
/**
*
* this interface is intended for {@code enums} (or similar classes that needs
* to be identified by a value) who are based on a value for each constant,
* where it has the utility methods to identify the type ({@code enum} constant)
* based on the value passed, and can declare it's value in the interface as
* well
*
* @param <T>
* the type of the constants (pass the {@code enum} as a type)
* @param <V>
* the type of the value which identifies this constant
*/
public interface Valueable<T extends Valueable<T, V>, V> {
/**
* get the Type based on the passed value
*
* @param value
* the value that identifies the Type
* @return the Type
*/
T getType(V value);
/**
* get the value that identifies this type
*
* @return a value that can be used later in {@link #getType(Object)}
*/
V getValue();
}
теперь вот пример для небольшого перечисления, реализующего этот интерфейс:
public enum AreaType implements Valueable<AreaType, Integer> {
NONE(0),
AREA(1),
NEIGHBORHOOD(2);
private int value;
AreaType(int value) {
this.value = value;
}
@Override
public AreaType getType(Integer value) {
if(value == null){
// assume this is the default
return NONE;
}
for(AreaType a : values()){
if(a.value == value){ // or you can use value.equals(a.value)
return a;
}
}
// assume this is the default
return NONE;
}
@Override
public Integer getValue() {
return value;
}
}
сохранить это перечисление в Json:
AreaType areaType = ...;
jsonObject.put(TAG,areaType.getValue());
сейчас, чтобы получить значение из объекта Json:
int areaValue = jsonObject.optInt(TAG,-1);
AreaType areaType = AreaType.NONE.getType(areaValue);
так, если areaValue является 1, например, AreaType будет «Area», и так далее
взглянуть на эту ссылку: http://stackoverflow.com/questions/7766791/serializing -enums-with-jackson –