这与我之前在此问过的上一个问题有关
我试图解析相同的JSON,但现在我已经改变了我的类.
{
"lower": 20,
"upper": 40,
"delimiter": " ",
"scope": ["${title}"]
}
Run Code Online (Sandbox Code Playgroud)
我的课现在看起来像:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
此代码抛出异常,
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
Run Code Online (Sandbox Code Playgroud)
异常是可以理解的,因为根据我之前的问题的解决方案,GSON期望实际上将Enum对象创建为
${title}("${title}"),
${description}("${description}"); …Run Code Online (Sandbox Code Playgroud) 我想弄清楚如何反序列化一个 EnumMap。到目前为止,我一直在将 Gson 库用于其他所有方面,并且取得了成功。事实证明这很困难。
这是一个基本的想法:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;
enum FRUIT {
APPLE, BANANA
}
EnumMap<FRUIT, String> fruitMap;
Gson gson = new Gson();
public void setFruitMap(String jsonString){
Type typeToken = new TypeToken<EnumMap<FRUIT, String>>(){}.getType();
fruitMap = gson.fromJson(jsonString, typeToken);
}
String fruitMapString = "{ \"BANANA\":\"tasty!\", \"APPLE\":\"gross!\" }";
setFruitMap(fruitMapString); //Error occurs here.
assertEquals("tasty!", fruitMap.get(FRUIT.BANANA));
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我得到一个 java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.EnumMap
所以在我看来,Gson 库并没有创建 EnumMap,而是在创建 LinkedHashMap 后尝试进行转换。
所以我想我会去制作我自己的反序列化逻辑。下面是一个执行工作。但是..它有点笨拙。
public JsonDeserializer<EnumMap<FRUIT, String>> deserializeFruitMap(){
return new JsonDeserializer<EnumMap<FRUIT, String>>(){
@Override
public EnumMap<FRUIT, …Run Code Online (Sandbox Code Playgroud)