2015-11-24 182 views
0

我想實現在斯卡拉傑克遜映射隱式轉換可見,Scala的隱式轉換不是類型

的代碼看起來像這樣:

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

您不能導入映射所以要儘量改變'進口JacksonSerializer._' –

回答

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)