Why does Gson parse an Integer as a Double?

Gson is a simple parser. It uses always Double as a default number type if you are parsing data to Object.

Check this question for more information: How to prevent Gson from expressing integers as floats

I suggest you to use Jackson Mapper. Jackson distinguish between type even if you are parsing to an Object:

  • "2" as Integer
  • "2.0" as Double

Here is an example:

Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("data", "{\"rowNum\":0,\"colNum\":2,\"text\":\"math\"}");
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};

HashMap<String, Object> o = mapper.readValue(hashMap.get("data").toString(), typeRef);

maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>

JSON makes no distinction between the different type of numbers the way Java does. It sees all kind of numbers as a single type.

That the numbers are parsed as a Double is an implementation detail of the Gson library. When it encounters a JSON number, it defaults to parsing it as a Double.

Instead of using a Map, it would be better to define a POJO that encapsulates all fields of the JSON structure. This makes it much easier to access the data afterwards and the numbers are automatically parsed as an Integer.

class Cell {
    private Integer rowNum;
    private Integer colNum;
    private String text;
}

public static void main(String[] args) throws Exception {
    Map<String, Object> hashMap = new HashMap<String, Object>();
    hashMap.put("data", "{\"rowNum\":0,\"colNum\":2,\"text\":\"math\"}");

    Cell cell = new Gson().fromJson(hashMap.get("data").toString(), Cell.class);
    System.out.println(cell);
}

Tags:

Java

Json

Gson