This is related to a previous question that I asked here earlier

JSON parsing using Gson

我试图解析同一个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;
    }
}

This code throws an exception,

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}");

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

推荐答案

the documentation for Gson:

Gson provides default serialization and deserialization for Enums... If you would prefer to change the default representation, you can do so by registering a type adapter through GsonBuilder.registerTypeAdapter(Type, Object).

Following is one such approach.

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;
  }
}

Json相关问答推荐

将嵌套的json中的字符串强制转换为数字

在Ansible中从json中提取特定数据

419(未知状态)使用laravel处理PUT请求

将 std::可选值存储到 json 文件 C++

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

转换为Json时忽略内部对象中的数组

使用 Groovy 将 XML 转换为 JSON

jq: Select 何时来自另一个数组的值与此 json 中的值匹配

无法在Kotlin 中解析JSONObject

Powershell 无法从名为 count 的键中获取价值

如何使用 jq 返回此 JSON 文件的文本字段?

如何使用 jackson 反序列化为 Kotlin 集合

如何在不解析的情况下在javascript中同步包含JSON数据?

没有默认构造函数的杰克逊第 3 方类

JSON 到 JSON 转换器

为不同类型的项目数组正确的 JSON Schema

将序列化表单的数据转换为 json 对象

如何判断 JSON 响应元素是否为数组?

as_json 没有在关联上调用 as_json

带有 Jackson 的不可变 Lombok 注释类