播放案例类的 json 读取和默认参数? [英] Play json Read and Default parameters for case class?
本文介绍了播放案例类的 json 读取和默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用默认参数和使用 Play Json Read 时遇到问题.这是我的代码:
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(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 中提供参数,为什么它没有默认值?如何实现我想要的?
Why is this so? If I didn't provide parameter in the json why it didn't got default value? How to achieve what I want?
推荐答案
看起来好像支持默认参数是在 2.6.
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 _)
这篇关于播放案例类的 json 读取和默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文