scala - 如果存在隐式 Json 转换器,则进行 2.2 比赛

标签 scala playframework-2.2

我已将所有 Json 转换器放在一个文件 JsonUtil 中,然后有一个 ConvertToJson 方法,该方法尝试转换传递给 json 的任何对象。

基本上是这样的结构:

implicit val format_A = format[A]
implicit val format_B = format[B]

def convertToJson(o: Any): JsValue =
  o match {
    case a: A => Json.toJson(a)
    case b: B => Json.toJson(b)
    case a: Any => Logger.warn("could not convert to json: "+a); JsNull
  }

但有更多的格式化程序/案例。当我需要转换时(出于各种原因),我不想导入所有这些隐式。如果存在有效的 toJson 转换,是否有办法进行匹配,这样我就不必编写所有案例?

喜欢:

case o: ExistJsonConversion => Json.toJson(o)

最佳答案

这有效。

  def convertToJson[A](a: A)(implicit ev: Format[A] = null): JsValue = {
    if (ev != null) {
      Json.toJson(a)(ev)
    } else {
      println("oops")
      JsNull
    }
  }

下面是一个更好的版本(也许;)

  case class Perhaps[E](value: Option[E]) {
    def fold[F](ifAbsent: => F)(ifPresent: E => F): F = 
      value.fold(ifAbsent)(ifPresent)
  }

  implicit def perhaps[E](implicit ev: E = null) = Perhaps(Option(ev))

  def convertToJson[A](a: A)(implicit p: Perhaps[Format[A]]): JsValue = {
    p.fold[JsValue] {
      println("oops")
      JsNull
    } { implicit ev =>
      Json.toJson(a)
    }
  }

关于scala - 如果存在隐式 Json 转换器,则进行 2.2 比赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015658/

相关文章:

scala - 为什么 ((_ : Int, _ : Int) => _/_) not compile when ((_: Int)/(_: Int)) does?

Play 框架中的 Scalastyle "Public method must have explicit type"

java - Playframework 从服务器获取客户端 IP,而不是从 cookie

scala - Play Framework 2.2 - 找不到参数超时的隐式值

斯卡拉 REPL : Where to find documentation on particular command?

c# - 为什么相同的算法在 Scala 中的运行速度比在 C# 中慢得多?以及如何让它更快?

generics - scala 中参数化方法的类型覆盖

java - 无法从 Play 框架发送电子邮件

java - 在 Java、Play Framework 2.2.1 中 Gzip 文件

json - 在 Play Framework Scala 中列出 Json