有一个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
。
我尝试使用很多不同的JsonDeserializer
和TypeAdapter
来自定义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();
}
使用registerTypeAdapter
和registerTypeHierarchyAdapter
方法注册,但看起来他们的代码不是执行事件。我试图从我的TypeAdapter
或JsonDeserializer
代码中打印一些东西 - 它没有打印,代码执行也没有在代码中的断点处停止。
Gson版本:2.2.4