Why does Gson parse an Integer as a Double?

a 夏天 提交于 2019-12-30 17:31:51

问题


A complex json string and I want to convert it to map, I have a problem.

Please look at this simple test:

public class Test {

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

        Map<String,Object> dataMap = JsonUtil.getGson().fromJson(
                hashMap.get("data").toString(),new TypeToken<Map<String,Object>>() {}.getType());

        System.out.println(dataMap.toString());

    }
}

result:
console print : {rowNum=0.0, colNum=2.0, text=math}
Int is converted to Double;
Why does gson change the type and how can I fix it?


回答1:


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>



回答2:


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);
}


来源:https://stackoverflow.com/questions/45734769/why-does-gson-parse-an-integer-as-a-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!