对我来说,我创建了一个接口,该接口应该由我必须在 Json 中使用的任何枚举实现,这个接口强制枚举从一个值中知道正确的枚举本身,并且它应该返回一个值......所以每个 enum.CONSTANT 都映射到任何类型的值(无论是数字还是字符串)
所以当我想把这个枚举放在一个 Json 对象中时,我要求 enum.CONSTANT 给我它的值,当我有这个值(来自 Json)时,我可以请求枚举给我正确的enum.CONSTANT 映射到这个值
界面如下(可以照原样复制):
/**
*
* 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”,以此类推