Play json Read and Default parameters for case class?

前端 未结 3 412
一个人的身影
一个人的身影 2021-01-06 17:09

I have a problem with default parameters and using Play Json Read. Here is my code:

  case class Test(action: String, storeResult: Option[Boolean] = Some(tru         


        
相关标签:
3条回答
  • 2021-01-06 17:18

    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 _)
    
    0 讨论(0)
  • 2021-01-06 17:22

    It looks as if support for default parameters is in version 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 _)
    
    0 讨论(0)
  • 2021-01-06 17:35

    in Play 2.6 you can write simply:

    Json.using[Json.WithDefaultValues].reads[Test]
    
    0 讨论(0)
提交回复
热议问题