为案例类播放json读取和默认参数?

ser*_*eda 2 json scala playframework playframework-2.0

我有默认参数和使用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)
  }
Run Code Online (Sandbox Code Playgroud)

我最终希望得到的是

Test("Test", Some(true), Some(true))
Run Code Online (Sandbox Code Playgroud)

但我得到了:

Test("Test",None,None)
Run Code Online (Sandbox Code Playgroud)

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

Ali*_*ich 6

在Play 2.6中你可以写简单:

Json.using[Json.WithDefaultValues].reads[Test]
Run Code Online (Sandbox Code Playgroud)