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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With