播放 JSON - 如何在 Scala 中将其生成以进行 Json 处理?
Play JSON - How to generify this in Scala for Json handling?
我目前在 scala 中有这个,它可以满足我的要求:
private def prepareResponse(response: Array[SomeItem]): String = {
implicit val writes = Json.writes[SomeItem]
Json.stringify(JsObject(Map("message" -> Json.toJson(response))))
}
但是,我想对此进行泛化,以便我可以将其作为响应放入任何内容,并且只要为我尝试转换为 Json 的类型定义了 Json.writes ,它会将其字符串化。
例如:
private def prepareResponse(response: Any): String = {
implicit val writes = Json.writes[SomeItem]
implicit val writes2 = Json.writes[SomeOtherItem]
...
Json.stringify(JsObject(Map("message" -> Json.toJson(response))))
}
当然,这是行不通的,因为它表示没有为 Any
定义隐式写入。为 Any
添加一个也不起作用,因为我收到错误:
No unapply or unapplySeq function found
[scalac-2.11] implicit val writeAny = Json.writes[Any]
[scalac-2.11]
以 "right" 方式(如果有)执行此操作的理想方法是什么?
提前致谢!
import play.api.libs.json._
case class SomeItem(a: String, b: String)
object SomeItem {
implicit val codec = Json.format[SomeItem]
}
case class SomeOtherItem(a: String, b: String, c: String)
object SomeOtherItem {
implicit val codec = Json.format[SomeOtherItem]
}
// ...
object PlayJson extends App {
def prepareResponse[T](response: T)(implicit tjs: Writes[T]): String = {
Json.stringify(JsObject(Map("message" -> Json.toJson(response))))
}
println(prepareResponse(SomeItem("aa", "bb")))
println(prepareResponse(SomeOtherItem("aa", "bb", "cc")))
// ...
}
我目前在 scala 中有这个,它可以满足我的要求:
private def prepareResponse(response: Array[SomeItem]): String = {
implicit val writes = Json.writes[SomeItem]
Json.stringify(JsObject(Map("message" -> Json.toJson(response))))
}
但是,我想对此进行泛化,以便我可以将其作为响应放入任何内容,并且只要为我尝试转换为 Json 的类型定义了 Json.writes ,它会将其字符串化。
例如:
private def prepareResponse(response: Any): String = {
implicit val writes = Json.writes[SomeItem]
implicit val writes2 = Json.writes[SomeOtherItem]
...
Json.stringify(JsObject(Map("message" -> Json.toJson(response))))
}
当然,这是行不通的,因为它表示没有为 Any
定义隐式写入。为 Any
添加一个也不起作用,因为我收到错误:
No unapply or unapplySeq function found
[scalac-2.11] implicit val writeAny = Json.writes[Any]
[scalac-2.11]
以 "right" 方式(如果有)执行此操作的理想方法是什么?
提前致谢!
import play.api.libs.json._
case class SomeItem(a: String, b: String)
object SomeItem {
implicit val codec = Json.format[SomeItem]
}
case class SomeOtherItem(a: String, b: String, c: String)
object SomeOtherItem {
implicit val codec = Json.format[SomeOtherItem]
}
// ...
object PlayJson extends App {
def prepareResponse[T](response: T)(implicit tjs: Writes[T]): String = {
Json.stringify(JsObject(Map("message" -> Json.toJson(response))))
}
println(prepareResponse(SomeItem("aa", "bb")))
println(prepareResponse(SomeOtherItem("aa", "bb", "cc")))
// ...
}