I am trying to implement an implicit converter for jackson mapper in scala,
The code looks like that:
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()
}
}
}
But when i try the following:
import JacksonSerializer.JacksonSerializer
Ok("{}".toJsonString)
I get a compilation error:
value toJsonString is not a member of String Ok("{}".toJsonString)
Tried just about anything i can think about and still not getting any progress.
You have to call the enclosing object differently from the implicit class inside it:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.