简体   繁体   English

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

[英]Play json Read and Default parameters for case class?

I have a problem with default parameters and using Play Json Read. 我有默认参数和使用Play Json Read的问题。 Here is my code: 这是我的代码:

  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)
  }

What I was hoping to get at the end is 我最终希望得到的是

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

but I got: 但我得到了:

Test("Test",None,None)

Why is this so? 为什么会这样? If I didn't provide parameter in the json why it didn't got default value? 如果我没有在json中提供参数,为什么它没有得到默认值? How to achieve what I want? 如何实现我想要的?

在Play 2.6中你可以写简单:

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

It looks as if support for default parameters is in version 2.6 . 看起来好像支持默认参数是在2.6版本中。

A workaround for prior versions is to do something like the following: 以前版本的解决方法是执行以下操作:

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 _)

Do you really need Options in your case class if you supply default values? 如果提供默认值,您是否真的需要案例类中的选项? Without Options the following code should work 没有选项,以下代码应该有效

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 _)

If you need Options then this code might work (not tested!) 如果您需要选项,则此代码可能有效(未经过测试!)

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 _)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM