为什么Gson将1反序列化为1.0?

时间:2012-09-05 14:34:14

标签: java json gson

Gson gson = new Gson();
System.out.println(gson.fromJson("1", Object.class));    //output:1.0
System.out.println(gson.fromJson("1", String.class));    //output:1
System.out.println(gson.fromJson("1", Integer.class));   //output:1

我正在尝试自定义反序列化程序来修复它,但仍无效:

Gson gson = new GsonBuilder().registerTypeAdapter(Object.class,new JsonDeserializer<Object>() {
    @Override
    public Object deserialize(JsonElement json, Type typeOfT,JsonDeserializationContext context)throws JsonParseException {
        return json.getAsInt();
    }
}).create();
System.out.println(gson.fromJson("1", Object.class));   //still 1.0

我在这里做错了吗?

3 个答案:

答案 0 :(得分:4)

JSON中没有整数。 1.0和1是相同的,除了1.0是明确的。

答案 1 :(得分:2)

如果您的目标类具有int成员,则它将反序列化为int。否则,如果您使用fromJson w / o参数,则将其强制转换为(int)。

答案 2 :(得分:1)

  

我在这里做错了吗?

你正在做一些你可能不需要的事情。而且,它确实是错误的,因为除了数字之外,它会打破一切。

IIRC,某些内置类型的Gson反序列化器(包括Object)不起作用。

每当你使用类似List<Integer>的东西时,json将被读作int,所以一切都很好。

在某些情况下,您可能会使用Something<Object>并希望获得Integer而不是Double,但我怀疑这样的代码是否合理。如果是,请为Something编写一个解串器并解决问题。