使用jackson-module-Scala,我尝试使用Long as key序列化和反序列化具有内部 Map 的对象,但是 Jackson 将 key 序列化为 String 并且如果忽略 Class 中定义的类型,则不会将其反序列化为 Long 。是BUG吗?难道我做错了什么?
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
case class InnerMap(map: Map[Long, Long])
object CrazyJackson {
def main(args: Array[String]): Unit = {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
val innerMap = InnerMap(Map(1L->1L))
val serialized = mapper.writeValueAsString(innerMap)
val newObj = mapper.readValue(serialized, classOf[InnerMap])
println(serialized) // Why the key is serialized as a String?
println(innerMap)
println(newObj)
assert(newObj == innerMap)
}
}
断言失败并且 println(serialized) 语句的输出是:
{"map":{"1":1}}
奇怪的是打印newObj和innerMap是一样的:
InnerMap(Map(1 -> 1))
InnerMap(Map(1 -> 1))
正如@Varren 所说,问题确实出在断言中。但:
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import org.scalatest.FunSuite
class CrazyJacksonTest extends FunSuite {
test("test json comparision") {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
val innerMap = InnerMap(Map(1L->1L))
val serialized = mapper.writeValueAsString(innerMap)
val newObj = mapper.readValue(serialized, classOf[InnerMap])
assert(newObj.map == innerMap.map)
}
}
断言结果:
Map("1" -> 1) did not equal Map(1 -> 1)
ScalaTestFailureLocation: CrazyJacksonTest$$anonfun$1 at (CrazyJacksonTest.scala:17)
Expected :Map(1 -> 1)
Actual :Map("1" -> 1)
我搞不清楚了!地图必须是 Map[Long,Long]!
由于 Spark 依赖项,我必须使用此版本:
- 斯卡拉 2.11.11
- jackson-module-scala 2.6.5 并使用 2.9.1 版本进行测试,结果相同。
其他信息: