0

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.

1
  • 2
    I think your bug is elsewhere. Where is someMap populated? Commented Jan 18, 2017 at 7:54

1 Answer 1

1

This happens because your map contains Doubles instead of Longs. 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"])

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.