播放 json 读取案例 class 的默认参数?

Play json Read and Default parameters for case class?

我在使用默认参数和使用 Play Json Read 时遇到问题。 这是我的代码:

  case class Test(action: String, storeResult: Option[Boolean] = Some(true), returndata: Option[Boolean] = Some(true))

  val json =
    """
      {"action": "Test"}"""

  implicit val testReads: Reads[Test] =
    (
      (JsPath \ "action").read[String](minLength[String](1)) and
        (JsPath \ "store_result").readNullable[Boolean] and
        (JsPath \ "returndata").readNullable[Boolean]
      ) (Test.apply _)
  val js = Json.parse(json)

  js.validate[Test] match {
    case JsSuccess(a, _) => println(a)
    case JsError(errors) =>
      println("Here")
      println(errors)
  }

最后我希望得到的是

Test("Test", Some(true), Some(true))

但我得到了:

Test("Test",None,None)

为什么会这样?如果我没有在 json 中提供参数,为什么它没有得到默认值?如何实现我想要的?

似乎在版本 2.6 中支持默认参数。

以前版本的解决方法是执行如下操作:

object TestBuilder {
  def apply(action: String, storeResult: Option[Boolean], returndata: Option[Boolean]) =
    Test(
      action, 
      Option(storeResult.getOrElse(true)), 
      Option(returndata.getOrElse(true))
    )
}

implicit val testReads: Reads[Test] =
  (
    (JsPath \ "action").read[String](minLength[String](1)) and
    (JsPath \ "store_result").readNullable[Boolean] and
    (JsPath \ "returndata").readNullable[Boolean]
  )(TestBuilder.apply _)

如果您提供默认值,您真的需要选项 class 吗?如果没有选项,以下代码应该可以工作

case class Test(action: String, storeResult: Boolean = true, returndata: Boolean = true)

  implicit val testReads: Reads[Test] =
    (
      (JsPath \ "action").read[String](minLength[String](1)) and
        ((JsPath \ "store_result").read[Boolean]  or Reads.pure(true)) and
        ((JsPath \ "returndata").read[Boolean] or Reads.pure(true))
      ) (Test.apply _)

如果您需要选项,那么此代码可能有效(未测试!)

case class Test(action: String, storeResult: Option[Boolean] = Some(true), returndata: Option[Boolean] = Some(true))


  implicit val testReads: Reads[Test] =
    (
      (JsPath \ "action").read[String](minLength[String](1)) and
        ((JsPath \ "store_result").read[Boolean]  or Reads.pure(true)).map(x=>Some(x)) and
        ((JsPath \ "returndata").read[Boolean] or Reads.pure(true)).map(x=>Some(x))
      ) (Test.apply _)

在 Play 2.6 中你可以简单地写成:

Json.using[Json.WithDefaultValues].reads[Test]