Play 2.2 match if there exists an implicit Json converter

北慕城南 提交于 2019-12-01 08:16:59

This works.

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

A bit better version below (perhaps ;)

  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)
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!