无法使用Gson(Java)将反序列化对象强制转换回整数数组

时间:2016-04-22 11:53:58

标签: java gson deserialization

我正在尝试反序列化一个对象,但抛出了以下异常

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
    }

}

0 个答案:

没有答案