我正在尝试反序列化一个对象,但抛出了以下异常
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [I
at TestEnumMapDeserialization.main(TestEnumMapDeserialization.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
这是我的代码
enum Field {
@SerializedName("ids")
IDS,
@SerializedName("type")
TYPE;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
class Cmd {
Map<Field,Object> args;
public Map<Field,Object> getArgs() {
return args;
}
public void setArgs(Map<Field,Object> args) {
this.args = args;
}
}
public class TestEnumMapDeserialization {
public static void main(String[] args) {
Map<Field,Object> args2 = new HashMap<>();
args2.put(Field.IDS, new int[]{1,3,5});
Cmd cmd = new Cmd();
cmd.setArgs(args2);
Gson gson = new Gson();
String json = gson.toJson(cmd);
System.out.println(json); // {"args":{"ids":[1,3,5]}}
Cmd cm2 = gson.fromJson(json, Cmd.class);
int[] ids = (int[]) cm2.getArgs().get(Field.IDS); // here the error happens
}
}