Why is Gson deserialized from 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 am trying to configure a deserializer to fix it, but still does 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?

+5
source share
3 answers

Am I doing something wrong here?

You do what you most do not need. Moreover, this is really wrong, because it breaks for everything except numbers.

IIRC, Gson deserializers for some built-in types (including Object) do not work.

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

, Something<Object> Integer, Double , , . , , Something .

+1

JSON . 1.0 1 - , 1.0 .

+4

If your target class has int members, it will deserialize to int. Otherwise, just add it to (int) if you use Json parameters without parameters.

+2
source

All Articles