Skip to content

Gson doesn't deserialise Long numbers correctly #1084

@xavix-yo

Description

@xavix-yo

Gson shouldn't cast a number to a Double if a number does not have decimal digits. It's clearly wrong.

public class GsonVsJackson {


    public static void main(String[] args) throws Exception {
        testGson();
        System.out.println("========================");
        testJackson();
    }

    public static void testGson() {
        System.out.println("Testing Gson 2.8");
        Gson gson = new Gson();
        HashMap<String, Object> newTest = new HashMap<>();
        newTest.put("first", 6906764140092371368L);
        String jsonString = gson.toJson(newTest);
        System.out.println(jsonString); // output ok: {"first":6906764140092371368}
        Map<String, Object> mapFromJson = gson.fromJson(jsonString, Map.class);
        Number numberFromJson = (Number) mapFromJson.get("first");
        System.out.println(numberFromJson.getClass() + " = " + numberFromJson); // java.lang.Double val 6.9067641400923709E18
        long longVal = numberFromJson.longValue();
        System.out.println(longVal); // output rounded: 6906764140092370944
    }

    public static void testJackson() throws Exception {
        System.out.println("Testing Jackson");
        ObjectMapper jackson = new ObjectMapper();
        HashMap<String, Object> newTest = new HashMap<>();
        newTest.put("first", 6906764140092371368L);
        String jsonString = jackson.writeValueAsString(newTest);
        System.out.println(jsonString); // output ok: {"first":6906764140092371368}
        Map<String, Object> mapFromJson = jackson.readValue(jsonString, Map.class);
        Number numberFromJson = (Number) mapFromJson.get("first");
        System.out.println(numberFromJson.getClass() + " = " + numberFromJson); // java.math.BigInteger = 6906764140092371368
        long longVal = numberFromJson.longValue();
        System.out.println(longVal); // output OK: 6906764140092371368
    }

}

Kind Regards,
Daniele

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions