Skip to content
Advertisement

How can I prevent gson from converting integers to doubles

I’ve got integers in my json, and I do not want gson to convert them to doubles. The following does not work:

JavaScript

The output is not what I want:

JavaScript

Is there a way to have Integers instead of Doubles in my Map?

JavaScript

Edit: not all my fields are integer. I’ve modified my example accordingly. I’ve read quite a few examples online, including some answers on this site, but it does not work in this particular case.

Advertisement

Answer

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:

JavaScript

So you can try approach with custom deserializer for Map<String, Object> (or some more generic map if you want) :

JavaScript

To use it you will have to give proper TypeToken to registerTypeAdapter and gson.fromJson function:

JavaScript

Result:

JavaScript

PS: It is just one more option you can try. Personally i feel like creating custom object for your json instead of List<Map<String, Integer>> is much cooler and easier to read way

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement