转换 PlayJSON 映射中的值
Transform Value In PlayJSon Mapping
我正在使用 PlayJson 执行 JSON 到案例 class 的标准映射。如果验证成功,我想转换映射到成员的值,Test.foo
下面。是否可以将其用于 Reads 转换器的定义?
val json = .....
case class Test(foo:String, bar:String)
val readsTest: Reads[Test] = (
(__ \ "foo").read[String](minLength(5)) and // And I want to transform this value if the validation succeeds
(__ \ "bar").read[String](minLength(10))
)(Test.apply _)
json.validate[Test] match {
case s: JsSuccess[Test] => s.get
case e: JsError => false
}
Reads.map
可以做到这一点,例如,假设我们想要反转 foo
字段的值,那么我们可以在 Reads
上调用 .map(v => v.reverse)
所以
(__ \ "foo").read[String](minLength[String](5)).map(v => v.reverse)
这是一个工作示例
val json =
"""
|{
| "foo": "abcdefghijkl",
| "bar": "012345678910"
|}
|""".stripMargin
case class Test(foo: String, bar: String)
val readsTest: Reads[Test] = (
(__ \ "foo").read[String](minLength[String](5)).map(v => v.reverse)
(__ \ "bar").read[String](minLength[String](10))
)(Test.apply _)
Json.parse(json).validate[Test](readsTest)
输出
JsSuccess(Test(lkjihgfedcba,012345678910),)
我正在使用 PlayJson 执行 JSON 到案例 class 的标准映射。如果验证成功,我想转换映射到成员的值,Test.foo
下面。是否可以将其用于 Reads 转换器的定义?
val json = .....
case class Test(foo:String, bar:String)
val readsTest: Reads[Test] = (
(__ \ "foo").read[String](minLength(5)) and // And I want to transform this value if the validation succeeds
(__ \ "bar").read[String](minLength(10))
)(Test.apply _)
json.validate[Test] match {
case s: JsSuccess[Test] => s.get
case e: JsError => false
}
Reads.map
可以做到这一点,例如,假设我们想要反转 foo
字段的值,那么我们可以在 Reads
上调用 .map(v => v.reverse)
所以
(__ \ "foo").read[String](minLength[String](5)).map(v => v.reverse)
这是一个工作示例
val json =
"""
|{
| "foo": "abcdefghijkl",
| "bar": "012345678910"
|}
|""".stripMargin
case class Test(foo: String, bar: String)
val readsTest: Reads[Test] = (
(__ \ "foo").read[String](minLength[String](5)).map(v => v.reverse)
(__ \ "bar").read[String](minLength[String](10))
)(Test.apply _)
Json.parse(json).validate[Test](readsTest)
输出
JsSuccess(Test(lkjihgfedcba,012345678910),)