I\'ve got integers in my json, and I do not want gson to convert them to doubles. The following does not work:
@Test
public void keepsIntsAsIs(){
String
Streaming version of @varren's answer:
class CustomizedObjectTypeAdapter extends TypeAdapter
It is modified version of ObjectTypeAdapter.java. These original lines:
case NUMBER:
return in.nextDouble();
are replaced by this:
case NUMBER:
String n = in.nextString();
if (n.indexOf('.') != -1) {
return Double.parseDouble(n);
}
return Long.parseLong(n);
In this code, number is read as string and number's type is selected based on existence of dot: number is double only if it has a dot in its string representation and it is long otherwise. Such solution preserves original values of source JSON.
This modified adapter could be used as universal if you could register it for Object type but Gson prevents it:
// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);
You have to register this type adapter to those types that you need, e.g. Map and List:
CustomizedObjectTypeAdapter adapter = new CustomizedObjectTypeAdapter();
Gson gson = new GsonBuilder()
.registerTypeAdapter(Map.class, adapter)
.registerTypeAdapter(List.class, adapter)
.create();
Now Gson can deserialize numbers as is.