我有这个 json,我一直在用json4s解析和替换字段,json 看起来像这样:
{
"id": "6988",
"signatories": [
{
"fields": [
{
"name": "fstname",
"value": "Bruce"
},
{
"name": "sndname",
"value": "Lee"
},
{
"name": "email",
"value": "bruce.lee@company.com"
},
{
"name": "sigco",
"value": "Company"
},
{
"name": "mobile",
"value": "0760000000"
}
]
},
{
"fields": [
{
"name": "fstname",
"value": ""
},
{
"name": "sndname",
"value": ""
},
{
"name": "email",
"value": ""
},
{
"name": "mobile",
"value": ""
},
{
"name": "sigco",
"value": ""
}
]
}
]
}
第二个数组称为“字段”,这是我想用实际字符串值替换空字符串的数组。我一直在使用json4s transformField 函数执行此操作,首先将 json 解析为 JObject,然后使用新值转换 JObject。
val a = parse(json)
// transform the second occurance of fields (fields[1])
val v = a.\("signatories").\("fields")(1).transform {
// Each JArray is made of objects. Find fields in the object with key as name and value as fstname
case obj: JObject => obj.findField(_.equals(JField("name", JString("fstname")))) match {
case None => obj //Didn't find the field. Return the same object back to the array
// Found the field. Change the value
case Some(x) =>
obj.transformField { case JField(k, v) if k == "value" => JField(k, JString("New name")) }
}
}
现在我得到了原始解析的 json“a”,并且得到了新的 JArray,其中包含“v”中的更新字段。我需要做的最后一件事是将新值合并到原始 JObject“a”中。我用替换试过这个,没有运气。
val merged = a.replace(List("fields"), v)
问题:
- 如何让 replace() 替换我第二次出现的字段数组?
- 有一个更好的方法吗?建议非常感谢。
这是完整的代码的可运行版本以及 json 的示例打印:http: //pastebin.com/e0xmxqFF