在使用 GSON 解析 JSON 时使用枚举

问题描述 投票:0回答:8

这与我之前在这里问过的问题有关

使用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 期望 Enum 对象实际上被创建为

${title}("${title}"),
${description}("${description}");

但是由于这在语法上是不可能的,那么推荐的解决方案、变通方法是什么?

java json gson
8个回答
377
投票

我想扩展一下 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
类的值配合得很好。就我而言,我已经从
Items
数组解析了
json
列表:

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

65
投票

来自 Gson 的文档

Gson 为 Enum 提供默认的序列化和反序列化...如果您希望更改默认表示形式,可以通过 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

15
投票

以下代码片段使用自 Gson 2.3 起可用的

Gson.registerTypeAdapter(...)
注释,消除了对显式
@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;
            }
        }
    }
}

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

0
投票

如果您想要自定义适配器将枚举与您自己的实现进行映射,那么您可以使用此方法并将您的实现添加到读取方法中,该方法接受字符串并返回您的自定义映射枚举。 在此示例中,我在货币 ENUM 中使用了“fromValue”方法。

public static class Adapter extends TypeAdapter<Currency> {
    @Override
    public void write(final JsonWriter jsonWriter, final Currency enumeration) throws IOException {
      jsonWriter.value(enumeration.getValue());
    }

    @Override
    public Currency read(final JsonReader jsonReader) throws IOException {
      Object value = jsonReader.nextString();
      return Currency.fromValue(String.valueOf(value));
    }
  }

要使用它,只需在 ENUM 类中添加此注释即可。

@JsonAdapter(Currency.Adapter.class)
public enum Currency {
...
}
© www.soinside.com 2019 - 2024. All rights reserved.