Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Gson deserialize 1 to 1.0?

Tags:

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

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?

like image 205
Koerr Avatar asked Sep 05 '12 14:09

Koerr


2 Answers

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

like image 154
Cubic Avatar answered Sep 22 '22 08:09

Cubic


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.

like image 37
kenyee Avatar answered Sep 25 '22 08:09

kenyee