简体   繁体   中英

Mapping Exception while serializing an object having a HashMap to JSON using Jackson

I have a class that I am trying to serialize to JSON using Jackson:

class A {
    String someString;
    Map<String, Long> someMap;
}

I am serializing using the following code:

mapper.writeValueAsString(a);

where a is an instance of class A.

I am getting this exception:

com.fasterxml.jackson.databind.JsonMappingException: java.lang.Double cannot be cast to java.lang.Long (through reference chain ... java.util.HashMap)

I have tried enabling different Default Typing, but that has not helped.

This happens because your map contains Double s instead of Long s. Usually that's a result of ignoring warnings or using reflection. It's fairly easy to reproduce:

A a = new A();
a.someMap = new HashMap<>();
((Map)a.someMap).put("bar", 1.0);
new ObjectMapper().writeValueAsString(a);

com.fasterxml.jackson.databind.JsonMappingException: java.lang.Double cannot be cast to java.lang.Long (through reference chain: A["someMap"]->java.util.HashMap["bar"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM