简体   繁体   中英

Why does Gson deserialize 1 to 1.0?

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

I'm trying to custom a deserializer to fix it,but still not work:

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

Am I doing something wrong here?

There are no integers in JSON. 1.0 and 1 are the same thing, except 1.0 is explicit.

If your destination class has int members, it'll deserialize into ints. Otherwise, just cast it to (int) if you're using fromJson w/o parameters.

Am I doing something wrong here?

You're doing something you most probably don't need. Moreover, it's really wrong, as it breaks for everything but numbers.

IIRC, Gson deserializers for some build-in types (including Object ) don't work.

Whenever you use something like List<Integer> , the json will be read as int, so everything's fine.

There might be some cases where you use Something<Object> and want to get Integer rather than Double there in, however I doubt if such a code makes sense. In case it does, write a deserializer for Something and fix the problem there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM