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
1) You have to create custom JsonDeserializer and not JsonSerializer like in your question.
2) I don't think this behavior comes from Double deserializer. it is more like json object/map problem
Here is from source code:
case NUMBER:
return in.nextDouble();
So you can try approach with custom deserializer for Map (or some more generic map if you want) :
public static class MapDeserializerDoubleAsIntFix implements JsonDeserializer
To use it you will have to give proper TypeToken to registerTypeAdapter and gson.fromJson function:
String json="[{\"id\":1,\"quantity\":2,\"name\":\"apple\"}, {\"id\":3,\"quantity\":4,\"name\":\"orange\"}]";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken
Result:
{id=1, quantity=2, name=apple}
{id=3, quantity=4, name=orange}
Serialized back to: [{"id":1,"quantity":2,"name":"apple"},{"id":3,"quantity":4,"name":"orange"}]
PS: It is just one more option you can try. Personally i feel like creating custom object for your json instead of List is much cooler and easier to read way