我正在以一种稍微"不同"的方式使用Gson,我想知道以下是否可能…
我想更改枚举的默认序列化/反序列化格式,以便它使用完全限定的类名,但保留对所述枚举的@SerializedName注释的支持。基本上,给定下面的enum…
package com.example;
public class MyClass {
public enum MyEnum {
OPTION_ONE,
OPTION_TWO,
@SerializedName("someSpecialName")
OPTION_THREE
}
}
I'd like the following to true…
gson.toJson(MyEnum.OPTION_ONE) == "com.example.MyClass.MyEnum.OPTION_ONE"
&&
gson.toJson(MyEnum.OPTION_TWO) == "com.example.MyClass.MyEnum.OPTION_TWO"
&&
gson.toJson(MyEnum.OPTION_THREE) == "someSpecialName"
,反之亦然。
(对于那些好奇的人,我试图建立一个小的库,允许我把android的intent的动作作为枚举,这样我就可以写开关语句,而不是一堆丑陋的if-else +字符串比较,我想支持注释,这样我也可以包括自定义的预先存在的动作字符串,如intent。)ACTION_VIEW等在同一个enum中)。
所以有人知道是否有可能注册一个类型适配器,如果@SerializedName字段存在,可以回落?我需要自己在TypeAdapter中检查annotation吗?
我为这个问题创建了一个很好的解决方案:
package your.package.name
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Field;
public class EnumAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
Class<? super T> rawType = type.getRawType();
if (rawType.isEnum()) {
return new EnumTypeAdapter<T>();
}
return null;
}
public class EnumTypeAdapter<T> extends TypeAdapter<T> {
public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
Enum<?> realEnums = Enum.valueOf(value.getClass().asSubclass(Enum.class), value.toString());
Field[] enumFields = realEnums.getClass().getDeclaredFields();
out.beginObject();
out.name("name");
out.value(realEnums.name());
for (Field enumField : enumFields) {
if (enumField.isEnumConstant() || enumField.getName().equals("$VALUES")) {
continue;
}
enumField.setAccessible(true);
try {
out.name(enumField.getName());
out.value(enumField.get(realEnums).toString());
} catch (Throwable th) {
out.value("");
}
}
out.endObject();
}
public T read(JsonReader in) throws IOException {
return null;
}
}
}
当然还有:
new GsonBuilder().registerTypeAdapterFactory(new EnumAdapterFactory()).create();
在谷歌上搜索了一下,找到了Gson的EnumTypeAdapter和相关的AdapterFactory的来源:https://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java#717
从它的外观,我将,事实上,必须手动检查@SerializedName属性,但它看起来很容易做到。我计划复制适配器和适配器工厂(几乎逐行),并修改name
的默认值(第724行),以包括完整的类名。
结果TypeAdapter看起来像这样…
private static final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
private final Map<String, T> nameToConstant = new HashMap<String, T>();
private final Map<T, String> constantToName = new HashMap<T, String>();
public EnumTypeAdapter(Class<T> classOfT) {
try {
String classPrefix = classOfT.getName() + ".";
for (T constant : classOfT.getEnumConstants()) {
String name = constant.name();
SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class);
if (annotation != null) {
name = annotation.value();
} else {
name = classPrefix + name;
}
nameToConstant.put(name, constant);
constantToName.put(constant, name);
}
} catch (NoSuchFieldException e) {
throw new AssertionError();
}
}
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return nameToConstant.get(in.nextString());
}
public void write(JsonWriter out, T value) throws IOException {
out.value(value == null ? null : constantToName.get(value));
}
}