jackson-module-scala
jackson-module-scala copied to clipboard
ClassCastException,bean include Long key of map in 2.7.2
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
class XX {
@beans.BeanProperty
var b = Map[String, Long]("1" -> 11L, "2" -> 22)
}
object XX {
def main(args: Array[String]) {
val mapper = new ObjectMapper with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
//
val x = new XX
val s = mapper.writeValueAsString(x)
println("s:" + s)
//
val mm = mapper.readValue[XX](s)
//
val rb = mm.b.get("1").get
println("get:" + rb)
println(rb == 11)
}
}
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long at scala.runtime.BoxesRunTime.unboxToLong(BoxesRunTime.java:105) at XX$.main(XX.scala:26) at XX.main(XX.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) s:{"b":{"1":11,"2":22}}
very confusing until I realized this is a bug. Can anyone give a reply ?
Unfortunately, due to the way jackson-module-scala uses Java reflection, there are issues with reference types that wrap primitives - eg Map[String, Long], Option[Long] (caused by type erasure). At the moment, the only workaround is to use a JsonDeserialize
annotation to provide the missing type information. See https://github.com/FasterXML/jackson-module-scala/pull/541 for an example.