2

我正在尝试使用 Scala,特别是json4s库以操作一些 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))))))

我现在面临的问题是:

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

例如(我知道这很可能不是 Scala 中的工作方式,但你会明白的)

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

1 回答 1

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
)))))) 

于 2015-01-14T08:22:28.940 回答