使用json4s在JArray中使用TransformField

时间:2015-01-14 07:33:10

标签: scala json4s

我正在尝试Scala,特别是json4s lib,以便操纵一些json。我对Scala和json4s的语法都很难过,以为我会问你们。

我有这个json,我需要更新一些字段,并将其完整地发送回服务。 json看起来像这样:

{
    "id": "6804",
    "signatories": [
        {
            "id": "12125",
            "fields": [
                {
                    "type": "standard",
                    "name": "fstname",
                    "value": "John"
                },
                {
                    "type": "standard",
                    "name": "sndname",
                    "value": "Doe"
                },
                {
                    "type": "standard",
                    "name": "email",
                    "value": "john.doe@somwhere.com"
                },
                {
                    "type": "standard",
                    "name": "sigco",
                    "value": "Company"
                }
            ]
        }
    ]
}

我正在使用json4s将其解析为JArray,如下所示:

import org.json4s._
import org.json4s.native.JsonMethods._

val data = parse(json)
val fields = (data \ "signatories" \ "fields")

这给了我一个包含所有字段的JArray :(非常抱歉格式化)

JArray(List(JObject(List((type,JString(standard)), (name,JString(fstname)), (value,JString(John)))), JObject(List((type,JString(standard)), (name,JString(sndname)), (value,JString(Doe)))), JObject(List((type,JString(standard)), (name,JString(email)), (value,JString(john.doe@somwhere.com)))), JObject(List((type,JString(standard)), (name,JString(sigco)), (value,JString(Company))))))

我现在面临的问题是:

如何查找每个字段属性“name”,并将其(转换)更改为新值?

例如(我知道这不是它在Scala中的工作原理,但你会得到这个想法)

foreach(field in fields) {
     if(field.name == 'fstname') {
          field.value = "Bruce"
     }
}

1 个答案:

答案 0 :(得分:2)

你可以尝试

val a = JArray(List(JObject(....))) // Same as your JArray<pre><code>   

a.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("Bruce")) } 
}
}    

结果 -


res0: org.json4s.JValue = JArray(List(JObject(List((typ,JString(standard)), (name,JString(fstname)), (value,JString(Bruce)))), JObject(List((typ,JString(standard)), (name,JString(sndname)), (
ring(Doe)))), JObject(List((typ,JString(standard)), (name,JString(email)), (value,JString(john.doe@somwhere.com)))), JObject(List((typ,JString(standard)), (name,JString(sigco)), (value,JStrin
))))))