我有一个枚举:
enum Type {
LIVE, UPCOMING, REPLAY
}
还有一些 JSON:
{
"type": "live"
}
还有一个类:
class Event {
Type type;
}
当我尝试使用 GSON 反序列化 JSON 时,我收到null
了Event
type 字段,因为 JSON 中 type 字段的大小写与枚举的大小写不匹配。
Events events = new Gson().fromJson(json, Event.class);
如果我将枚举更改为以下内容,则一切正常:
enum Type {
live, upcoming, replay
}
但是,我想将枚举常量全部保留为大写。
我假设我需要编写一个适配器,但没有找到任何好的文档或示例。
什么是最好的解决方案?
编辑:
我能够让 JsonDeserializer 工作。有没有更通用的方法来编写它,因为每次枚举值和 JSON 字符串之间的大小写不匹配时都必须编写它是很不幸的。
protected static class TypeCaseInsensitiveEnumAdapter implements JsonDeserializer<Type> {
@Override
public Type deserialize(JsonElement json, java.lang.reflect.Type classOfT, JsonDeserializationContext context)
throws JsonParseException {
return Type.valueOf(json.getAsString().toUpperCase());
}
}