Play 2.2 match if there exists an implicit Json converter

后端 未结 1 362
名媛妹妹
名媛妹妹 2021-01-14 06:07

I have put all my Json converters in one file JsonUtil, and then have a convertToJson method which tries to convert any object passed to json.

Basically a structure

相关标签:
1条回答
  • 2021-01-14 06:42

    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)
        }
      }
    
    0 讨论(0)
提交回复
热议问题