Is there a way to stop Scala 2.12 breaking the Jackson object mapper?
I am upgrading my version of Scala to 2.12 from 2.11 and the object mapper seems to break. Other parts of my code require features only available under 2.12.
This using scala 2.12 with spark 2.1 mentions rebuilding Jackson as a possible solution. Is this truely necessary or is there a simpler solution?
SBT configuration for Scala 2.11.0
// Identity
name := "ScalaJsonSpike00"
organization := "com.acme"
// Versions
version := "1.0"
scalaVersion := "2.11.0"
// Scala test
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % "test"
// JSON
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.8.8"
// https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-scala_2.11
libraryDependencies += "com.fasterxml.jackson.module" % "jackson-module-scala_2.11" % "2.8.8"
Code for both 2.11 and 2.12
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
object Main {
def main(args: Array[String]): Unit = {
val originalMap = Map("a" -> List(1,2), "b" -> List(3,4,5), "c" -> List())
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
println(mapper.writeValueAsString(originalMap))
}
}
Result with Scala 2.11.0
{"a":[1,2],"b":[3,4,5],"c":[]}
SBT configuration update to scala 2.12.1
scalaVersion := "2.12.1"
Result with Scala 2.12.1
com.intellij.rt.execution.application.AppMain Main
Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper.$init$(Lcom/fasterxml/jackson/module/scala/experimental/ScalaObjectMapper;)V
at Main$$anon$1.<init>(Main.scala:9)
at Main$.main(Main.scala:9)
at Main.main(Main.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:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Solution 1:
You should use %%
to get jackson-module-scala
: appropriate for your Scala version:
libraryDependencies += "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.8.8"
In your current version you always use Scala 2.11 version of this module, which is not binary compatible with Scala 2.12.
There is no such issue with core Jackson libraries, as those as Java ones, and therefore not affected by Scala version in any way.