Gson将整数数组反序列化为Doubles的ArrayList而不是整数的ArrayList(或int的数组)作为Map <string,object>的值

时间:2016-04-24 14:37:36

标签: java gson deserialization

有一个JSON字符串

{"uuid": "a1e55ef2-3a58-40d7-9ca2-49b0c3aa653c","args": {"ids": [5,77,999], type: "item_delete"}}

我试图反序列化到下面的类

class Foo {
    String uuid;
    Map<String,Object> args;
}

使用此代码

public static void main(String[] args) {
    String commandJson = ...;
    Gson gson = new Gson();
    Foo foo = gson.fromJson(commandJson, Foo.class);
}

然后,在调试器中,我可以看到ids属性表示为ArrayList<Double>,因此我可以看到5,77,999而不是5.0,77.0,999.0

我尝试使用很多不同的JsonDeserializerTypeAdapter来自定义GsonBuilder,例如

    GsonBuilder gsonBuilder = new GsonBuilder()
            .registerTypeHierarchyAdapter(Double.class, new JsonDeserializer<Integer>() { // also tried Number.class
                @Override
                public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    return null; // No implementation in this example as it is not even called
                }
             });
    Gson gson = gsonBuilder.create();

class IntegerTypeAdapter extends TypeAdapter<Integer> {
    @Override
    public void write(JsonWriter out, Integer value) throws IOException {
        System.out.println("hello from write");
    }
    @Override
    public Integer read(JsonReader in) throws IOException {
        System.out.println("hello from read");
        return null; // I didn't implement it as it looks like it is not even called
    }
}

public static void main(String[] args) {
    GsonBuilder gsonBuilder = new GsonBuilder()
            .registerTypeAdapter(Integer.class, new IntegerTypeAdapter());
        Gson gson = gsonBuilder.create();
}

使用registerTypeAdapterregisterTypeHierarchyAdapter方法注册,但看起来他们的代码不是执行事件。我试图从我的TypeAdapterJsonDeserializer代码中打印一些东西 - 它没有打印,代码执行也没有在代码中的断点处停止。

Gson版本:2.2.4

0 个答案:

没有答案