How to prevent Gson from expressing integers as floats

You’re telling Gson it’s looking for a list of maps of Strings to Objects, which essentially says for it to make a best guess as to the type of the Object. Since JSON doesn’t distinguish between integer and floating point fields Gson has to default to Float/Double for numeric fields.

Gson is fundamentally built to inspect the type of the object you want to populate in order to determine how to parse the data. If you don’t give it any hint, it’s not going to work very well. One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don’t use Hashtable!) and instead give Gson more information about the type of data it’s expecting.

class Response {
  int id;
  int field_id;
  ArrayList<ArrayList<Integer>> body; // or whatever type is most apropriate
}

responses = new Gson()
            .fromJson(draft, new TypeToken<ArrayList<Response>>(){}.getType());

Again, the whole point of Gson is to seamlessly convert structured data into structured objects. If you ask it to create a nearly undefined structure like a list of maps of objects, you’re defeating the whole point of Gson, and might as well use some more simplistic JSON parser.

Leave a Comment