这与我之前在此处提出的问题有关。
使用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}");
但是由于这在语法上是不可能的,那么有哪些推荐的解决方案或变通方法呢?
"1"
而不是简单的1
... - Matthew HousserSerializedName
不匹配,那么枚举将默认为null
。未知状态的默认行为可以在包装类中处理。但是,如果您需要代表“未知”的表示形式而不是null
,则需要编写自定义反序列化器或类型适配器。 - Peter F