Scala隐式转换器对于类型不可见

时间:2015-11-24 14:51:52

标签: java scala

我正在尝试在scala中为jackson mapper实现隐式转换器,

代码如下:

object JacksonSerializer {
    implicit val mapper = new ObjectMapper() with ScalaObjectMapper
    mapper.registerModule(DefaultScalaModule)
    implicit class JacksonDeSerializer(val body: AnyContent) extends AnyVal {
        def as[T](implicit manifest: Manifest[T]): T = {
          mapper.readValue(body.asText.get, manifest.runtimeClass.asInstanceOf[Class[T]])
        }
    }
    implicit class JacksonSerializer(val any: Any) {
        def toJsonString: String = {
          val out = new StringWriter
          mapper.writeValue(out, any)
          out.toString()
        }
    }
}

但是当我尝试以下内容时:

import JacksonSerializer.JacksonSerializer
Ok("{}".toJsonString)

我收到编译错误:

value toJsonString is not a member of String Ok("{}".toJsonString)

尝试了我能思考的任何事情,但仍未取得任何进展。

1 个答案:

答案 0 :(得分:2)

您必须以不同于其中隐式类的方式调用封闭对象:

object JacksonSerializerHelpers {
  implicit val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  implicit class JacksonSerializer(val any: Any) {
    def toJsonString(implicit mapper: ObjectMapper): String = {
      val out = new StringWriter
      mapper.writeValue(out, any)
      out.toString()
    }
   }
}

import JacksonSerializerHelper.JacksonSerializer
Ok("{}".toJsonString)