Scala Play json:功能操作错误

时间:2018-02-08 22:06:26

标签: scala playframework functional-programming play-json

编译以下代码时:

import $ivy.{ `com.typesafe.play::play-json:2.6.8` } // for ammonite users

import play.api.libs.json.{JsPath, Writes}

case class Collect(
    auto_redirect: Boolean,
    collect_shipping_address: Boolean,
    collect_phone_number: Boolean,
    collect_email: Boolean,
    collect_country: Boolean,
  )

import play.api.libs.functional.syntax._
lazy val writes: Writes[Collect]  = (
  (JsPath \ "auto_redirect").write[Boolean] and
  (JsPath \ "collect_shipping_address").write[Boolean] and
  (JsPath \ "collect_phone_number").write[Boolean] and
  (JsPath \ "collect_email").write[Boolean] and
  (JsPath \ "collect_country").write[Boolean]
)(Collect.unapply _)

我收到以下错误:

cmd4.sc:5: overloaded method value apply with alternatives:
  [B](f: B => (Boolean, Boolean, Boolean, Boolean, Boolean))(implicit fu: play.api.libs.functional.ContravariantFunctor[play.api.libs.json.OWrites])play.api.libs.json.OWrites[B] <and>
  [B](f: (Boolean, Boolean, Boolean, Boolean, Boolean) => B)(implicit fu: play.api.libs.functional.Functor[play.api.libs.json.OWrites])play.api.libs.json.OWrites[B]
 cannot be applied to (ammonite.$sess.cmd2.Collect => Option[(Boolean, Boolean, Boolean, Boolean, Boolean)])
  (JsPath \ "collect_email").write[Boolean] and

编辑:评论后更正。

2 个答案:

答案 0 :(得分:1)

问题是我忘了解除这个功能。它位于文档中:https://www.playframework.com/documentation/2.6.x/ScalaJsonCombinators#writes

  lazy val writes: Writes[Collect]  = (
    (JsPath \ "auto_redirect").write[Boolean] and
    (JsPath \ "collect_shipping_address").write[Boolean] and
    (JsPath \ "collect_phone_number").write[Boolean] and
    (JsPath \ "collect_email").write[Boolean] and
    (JsPath \ "collect_country").write[Boolean]
  )(unlift(Collect.unapply))

答案 1 :(得分:0)

您希望将service.coingate.model.Collect转换为JsonValue,但忘记在Collect中添加val writes字段的名称。

请查看Playframework中的Json writes documentation