1

Using jackson-module-Scala, I try to serialize and deserialize an object with an inner Map using a Long as key, but the Jackson serializes the key as String and doesn't deserialize it as Long ifgnoring the type efined in the Class. Is it a BUG? Am I doing something wrong?

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)
  }

}

The assert fails and the output of the println(serialized) statement is :

{"map":{"1":1}}

It is strange that printing newObj and innerMap is the same:

InnerMap(Map(1 -> 1))
InnerMap(Map(1 -> 1))

As @Varren says, the problem really is in the assert. But:

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)
  }
}

The assert result:

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)

I am lost! The map must be a Map[Long,Long]!

I must use this version because of Spark dependencies:

  • Scala 2.11.11
  • jackson-module-scala 2.6.5 and also test with version 2.9.1 with the same result.

Other info:

4

2 に答える 2