在gson中更改默认的枚举序列化和反序列化

6
我是用Gson以稍微“不同”的方式,并且我想知道以下是否可能...
我想要更改枚举的默认序列化/反序列化格式,以便它使用完全限定的类名,但保持对@SerializedName注释的支持。 基本上,考虑以下枚举...
package com.example;
public class MyClass {
    public enum MyEnum {

        OPTION_ONE, 

        OPTION_TWO, 

        @SerializedName("someSpecialName")
        OPTION_THREE
    }
}

我希望以下内容是正确的...

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的意图操作作为枚举来处理,以便我可以编写switch语句而不是一堆丑陋的if-else和字符串比较,并且我希望支持注释,以便我可以在同一个枚举中包含自定义预先存在的操作字符串,如Intent.ACTION_VIEW等)。

那么,有人知道是否可以注册一个类型适配器,如果存在@SerializedName字段,则会回退吗?我只需在自己的TypeAdapter中检查那个注释吗?

提前致谢。

2个回答

6
我为这个问题创建了一个相当不错的解决方案:

我为这个问题创建了一个相当不错的解决方案:

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();

希望这能帮到您!

5
我通过谷歌搜索找到了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));
    }
}

我会暂时不回答这个问题,以防其他人有更好的答案而不是复制粘贴。 - Geoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接