使用枚举类型解析JSON时如何使用GSON

152
这与我之前在此处提出的问题有关。 使用Gson解析JSON 我正在尝试解析相同的JSON,但现在我已经稍微改变了我的类。
{
    "lower": 20,
    "upper": 40,
    "delimiter": " ",
    "scope": ["${title}"]
}

我的类现在长这样:

public class TruncateElement {

   private int lower;
   private int upper;
   private String delimiter;
   private List<AttributeScope> scope;

   // getters and setters
}


public enum AttributeScope {

    TITLE("${title}"),
    DESCRIPTION("${description}"),

    private String scope;

    AttributeScope(String scope) {
        this.scope = scope;
    }

    public String getScope() {
        return this.scope;
    }
}

这段代码会抛出一个异常,

com.google.gson.JsonParseException: The JsonDeserializer EnumTypeAdapter failed to deserialized json object "${title}" given the type class com.amazon.seo.attribute.template.parse.data.AttributeScope
at 

这个异常很容易理解,因为根据我之前提出的问题的解决方案,GSON期望枚举对象实际上是这样创建的:

The exception is understandable, because as per the solution to my previous question, GSON is expecting the Enum objects to be actually be created as
${title}("${title}"),
${description}("${description}");

但是由于这在语法上是不可能的,那么有哪些推荐的解决方案或变通方法呢?

7个回答

370

我想稍微扩展一下NAZIK/user2724653的回答(针对我的情况)。以下是Java代码:

public class Item {
    @SerializedName("status")
    private Status currentState = null;

    // other fields, getters, setters, constructor and other code...

    public enum Status {
        @SerializedName("0")
        BUY,
        @SerializedName("1")
        DOWNLOAD,
        @SerializedName("2")
        DOWNLOADING,
        @SerializedName("3")
        OPEN
     }
}

在JSON文件中,你只需要一个字段"status": "N",其中N=0,1,2,3 - 取决于状态值。这就是全部内容,GSON可以很好地处理嵌套的enum类的值。在我的情况下,我已经从json数组中解析出了Items列表:

List<Item> items = new Gson().<List<Item>>fromJson(json,
                                          new TypeToken<List<Item>>(){}.getType());

34
这个答案完美地解决了所有问题,不需要类型适配器! - Lena Bru
5
当我使用Retrofit/Gson时,枚举值的SerializedName被添加了额外的引号。例如,服务器实际接收到的是"1"而不是简单的1... - Matthew Housser
22
如果带有状态5的JSON到达,会发生什么?有没有办法定义默认值? - DmitryBorodin
14
如果来自JSON的值与任何一个SerializedName不匹配,那么枚举将默认为null。未知状态的默认行为可以在包装类中处理。但是,如果您需要代表“未知”的表示形式而不是null,则需要编写自定义反序列化器或类型适配器。 - Peter F

65

Gson文档中可以了解到:

Gson为Enums提供默认的序列化和反序列化... 如果您想改变默认的表现形式,可以通过GsonBuilder.registerTypeAdapter(Type, Object)注册类型适配器来实现。

以下是一种这样的方法。

import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class GsonFoo
{
  public static void main(String[] args) throws Exception
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AttributeScope.class, new AttributeScopeDeserializer());
    Gson gson = gsonBuilder.create();

    TruncateElement element = gson.fromJson(new FileReader("input.json"), TruncateElement.class);

    System.out.println(element.lower);
    System.out.println(element.upper);
    System.out.println(element.delimiter);
    System.out.println(element.scope.get(0));
  }
}

class AttributeScopeDeserializer implements JsonDeserializer<AttributeScope>
{
  @Override
  public AttributeScope deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    AttributeScope[] scopes = AttributeScope.values();
    for (AttributeScope scope : scopes)
    {
      if (scope.scope.equals(json.getAsString()))
        return scope;
    }
    return null;
  }
}

class TruncateElement
{
  int lower;
  int upper;
  String delimiter;
  List<AttributeScope> scope;
}

enum AttributeScope
{
  TITLE("${title}"), DESCRIPTION("${description}");

  String scope;

  AttributeScope(String scope)
  {
    this.scope = scope;
  }
}

38

使用注解@SerializedName

@SerializedName("${title}")
TITLE,
@SerializedName("${description}")
DESCRIPTION

14
以下代码片段可以省略显式的 Gson.registerTypeAdapter(...),使用自 Gson 2.3 版本起提供的@JsonAdapter(class) 注释来实现(请参见评论pm_labs)。
@JsonAdapter(Level.Serializer.class)
public enum Level {
    WTF(0),
    ERROR(1),
    WARNING(2),
    INFO(3),
    DEBUG(4),
    VERBOSE(5);

    int levelCode;

    Level(int levelCode) {
        this.levelCode = levelCode;
    }

    static Level getLevelByCode(int levelCode) {
        for (Level level : values())
            if (level.levelCode == levelCode) return level;
        return INFO;
    }

    static class Serializer implements JsonSerializer<Level>, JsonDeserializer<Level> {
        @Override
        public JsonElement serialize(Level src, Type typeOfSrc, JsonSerializationContext context) {
            return context.serialize(src.levelCode);
        }

        @Override
        public Level deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            try {
                return getLevelByCode(json.getAsNumber().intValue());
            } catch (JsonParseException e) {
                return INFO;
            }
        }
    }
}

1
请注意,此注释仅在版本2.3及更高版本中才可用:https://google.github.io/gson/apidocs/index.html?com/google/gson/annotations/JsonAdapter.html - pm_labs
5
请注意将您的序列化器/反序列化器类添加到Proguard配置中,因为它们可能会被删除(这在我的情况下发生过)。 - TormundThunderfist
我遇到一个错误:@JsonAdapter的值必须是TypeAdapter或TypeAdapterFactory的引用。gson v2.5 - undefined

10

使用GSON 2.2.2版本,枚举类型的编组和解组将变得更加容易。

import com.google.gson.annotations.SerializedName;

enum AttributeScope
{
  @SerializedName("${title}")
  TITLE("${title}"),

  @SerializedName("${description}")
  DESCRIPTION("${description}");

  private String scope;

  AttributeScope(String scope)
  {
    this.scope = scope;
  }

  public String getScope() {
    return scope;
  }
}

3
如果您真的想使用Enum的序号值,可以注册类型适配器工厂来覆盖Gson的默认工厂。
public class EnumTypeAdapter <T extends Enum<T>> extends TypeAdapter<T> {
    private final Map<Integer, T> nameToConstant = new HashMap<>();
    private final Map<T, Integer> constantToName = new HashMap<>();

    public EnumTypeAdapter(Class<T> classOfT) {
        for (T constant : classOfT.getEnumConstants()) {
            Integer name = constant.ordinal();
            nameToConstant.put(name, constant);
            constantToName.put(constant, name);
        }
    }
    @Override public T read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        return nameToConstant.get(in.nextInt());
    }

    @Override public void write(JsonWriter out, T value) throws IOException {
        out.value(value == null ? null : constantToName.get(value));
    }

    public static final TypeAdapterFactory ENUM_FACTORY = new TypeAdapterFactory() {
        @SuppressWarnings({"rawtypes", "unchecked"})
        @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            Class<? super T> rawType = typeToken.getRawType();
            if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
                return null;
            }
            if (!rawType.isEnum()) {
                rawType = rawType.getSuperclass(); // handle anonymous subclasses
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}

然后只需注册工厂即可。
Gson gson = new GsonBuilder()
               .registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY)
               .create();

0

使用这个方法

GsonBuilder.enableComplexMapKeySerialization();

5
虽然这段代码可能回答了问题,但是提供更多关于它是如何解决问题的背景和/或原因会提高答案的长期价值。 - Nic3500
从gson 2.8.5开始,为了在枚举类型上使用SerializedName注释作为键,这是必需的。 - vazor

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