我正在从2.11将我的Scala版本升级到2.12,并且对象映射器似乎已经破解。我的代码的其他部分需要仅在2.12下提供的功能。
这using scala 2.12 with spark 2.1提到重建杰克逊作为一种可能的解决方案。这是真的必要还是有更简单的解决方案?
Scala 2.11.0的SBT配置
// 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"
2.11和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))
}
}
Scala 2.11.0的结果
{"a":[1,2],"b":[3,4,5],"c":[]}
SBT配置更新到scala 2.12.1
scalaVersion := "2.12.1"
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)
答案 0 :(得分:3)
您应该使用%%
获取jackson-module-scala
:适合您的Scala版本:
libraryDependencies += "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.8.8"
在您当前的版本中,您始终使用此模块的Scala 2.11版本,该版本与Scala 2.12不是二进制兼容的。
核心杰克逊库没有像Java那样的问题,因此不会以任何方式受到Scala版本的影响。