scala隐式传递给参数

scala implicit passing to parameter

要将 JsValue 转换为自定义值 Class,请使用此代码。

def Foo(today : String):String = {
    implicit def read (js: JsValue) : Reads[ResponseBasicModel[String]] = Reads[ResponseBasicModel[String]](
      js => JsSuccess(ResponseBasicModel[String](
        ReturnValue = js.\("ReturnValue").toString()
        )
      )
    )

    CallAPI[ResponseBasicModel[String]](
        "GET",
        "URL"
        ,15.second).ReturnValue
  }

调用API:

def CallAPI[A](httpMethod: String, subURL: String, timeout: FiniteDuration)(implicit m: scala.reflect.Manifest[A], read: Reads[A]) :A = {
/...
     Json.parse(robots.toString()).as[A]
}

但是return错误

Error:(20, 47) No Json deserializer found for type finance.remittance.data.ResponseBasicModel[String]. Try to implement an implicit Reads or Format for this type. return CallAPI[ResponseBasicModel[String]](

有什么解决办法吗?

我用这段代码解决了这个问题。

Writes 为空,因为我没有使用 writes 函数。

def Foo(today : String):String = {
    implicit object ResponseBasicModelFormat extends Format[ResponseBasicModel[String]]{
    def reads(js: JsValue) =JsSuccess(ResponseBasicModel[String](
        ReturnValue = js.\("ReturnValue").toString()
      ))
    def writes(res : ResponseBasicModel[String]): JsValue=null
  }

    CallAPI[ResponseBasicModel[String]](
        "GET",
        "URL"
        ,15.second).ReturnValue
  }