假设我有这样的JSON:
{
"name" : "Watership Down",
"location" : {
"lat" : 51.235685,
"long" : -1.309197
},
"residents" : [ {
"name" : "Fiver",
"age" : 4,
"role" : null
}, {
"name" : "Bigwig",
"age" : 6,
"role" : "Owsla"
} ]
}
如果我这样做
val transformer1 = (__ \ 'name).json.update(of[JsValue].map(a => JsString("x")))
将name
字段更改为"x"
它可以正常工作。
但如果我想以递归方式将所有名称更改为"x"
,我认为我可以使用递归jsPath,如下所示:
val transformerRecursive = (__ \\ 'name).json.update(of[JsValue].map(a => JsString("x")))
但是当我尝试它时,我收到了这个错误:
阶> jsobject.transform(transformerRecursive) res1:play.api.libs.json.JsResult [play.api.libs.json.JsObject] = JsError(List((// name,List(ValidationError(List(error.path.result.multiple),WrappedArray() )))))
如何在playframework中使用JSON Transformer的递归路径?
答案 0 :(得分:1)
正如@irundaia所说,你需要迭代数组并更新每个值(为此使用Reads.list
):
val t = (__ \ "residents").json.update(
Reads.list(
(__ \ "name").json.update(
Reads.pure(JsString("x"))
)
).map(JsArray)
)
scala> res1: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"name":"Watership Down","location":{"lat":51.235685,"long":-1.309197},"residents":[{"name":"x","age":4,"role":null},{"name":"x","age":6,"role":"Owsla"}]},/residents)
答案 1 :(得分:0)
由于@ andrey.ladniy,我设法解决了我想清空嵌套JsArray的问题。以下是如何完成此操作的示例,仅适用于可能会从任何帮助中找到的人:
import play.api.libs.json._
case class D(yay: String, nay: String)
case class C(ds: Seq[D], baz: Boolean)
case class B(cs: Seq[C], bar: Int)
case class A(b: B, foo: String)
implicit val formatD: OFormat[D] = Json.format
implicit val formatC: OFormat[C] = Json.format
implicit val formatB: OFormat[B] = Json.format
implicit val formatA: OFormat[A] = Json.format
val foo = A(
B(Seq(C(Seq(D("foo", "bar")), true), C(Seq(D("oof", "rab")), false)), 42),
"test"
)
val dsIgnoringReads =
(__ \ "b" \ "cs").json.update(Reads.seq((__ \ "ds").json.update(Reads.pure(JsArray()))).map(JsArray))
dsIgnoringReads.reads(Json.toJson(foo)).get
这产生
res0: play.api.libs.json.JsObject =
{"b":{"cs":[{"ds":[],"baz":true},{"ds":[],"baz":false}],"bar":42},"foo":"test"}