使用play-json库对Scala反序列化自定义scala对象

时间:2015-09-16 06:56:55

标签: scala deserialization play-json

在尝试将JSON字符串解析为自定义Scala对象时,我的ScalaTest中断了。我使用Play-Json库进行[de]序列化。序列化工作正常但反序列化在Blah类上运行单元测试时中断。该测试调用fromJsonString()方法,并使用ScalaTest库进行单元测试。在这里感谢一些帮助。

异常跟踪:(完整跟踪 - http://pasted.co/e627b1ee

An exception or error caused a run to abort: scala.collection.immutable.$colon$colon.hd$1()Ljava/lang/Object; 
java.lang.NoSuchMethodError: scala.collection.immutable.$colon$colon.hd$1()Ljava/lang/Object;
    at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:144)
    at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:108)
    at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:103)
    at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3536)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1872)
    at play.api.libs.json.jackson.JacksonJson$.parseJsValue(JacksonJson.scala:226)
    at play.api.libs.json.Json$.parse(Json.scala:21)
    at com.project.gateway.model.Blah.fromJsonString(Blah.scala:98)

Scala对象定义:

case class Blah(name: String, id: String) {

      implicit val BlahWrites: Writes[Blah] = (
        (JsPath \ "name").write[String] and
          (JsPath \ "id").write[String]
        )(unlift(Blah.unapply))

      implicit val BlahReads: Reads[Blah] = (
        (JsPath \ "name").read[String] and
          (JsPath \ "id").read[String]
        )(Blah)


      def toJsonString(): String = {
        Json.toJson(this).toString()
      }

      def fromJsonString(jsonString: String): Blah = {
        val value = Json.parse(jsonString)
        value.as[Blah]
        //Json.fromJson[Blah](value).get
      }
    }

我的SBT文件:

name := "Project"

version := "1.0"

scalaVersion := "2.11.7"

libraryDependencies += "com.typesafe.scala-logging" % "scala-logging_2.11" % "3.1.0"
libraryDependencies += "org.scalatest" % "scalatest_2.11" % "2.2.4" % "test"
libraryDependencies += "com.typesafe.play" % "play-json_2.10" % "2.4.2"

1 个答案:

答案 0 :(得分:2)

我猜运行/测试时scala-library的版本与用于构建依赖项的版本之间存在差异,这会引发错误。

如果使用SBT或Maven,您可以检查使用过的库(包括传递库),因此请检查scala库是否存在不兼容性(按不同的依赖关系引入不同版本)。