我在Scala中使用这种Json:
{
"ClientBase": [
{
"string#name": "robert",
"int#age": 46,
"string#country": "USA"
},
{
"string#name": "tom",
"int#age": 45,
"string#country": "UK"
}
]
}
我使用Json4s库,我想为每个客户端添加一个新字段。我知道如何为一个人做这个但是有一个快速的方法为每个人做这个吗?
我想得到这样的结果:
{
"ClientBase": [
{
"string#name": "robert",
"int#age": 46,
"string#country": "USA",
"BLOCK_ID" : "client_base"
},
{
"string#name": "tom",
"int#age": 45,
"string#country": "UK",
"BLOCK_ID" : "client_base"
}
]
}
答案 0 :(得分:0)
你能不能只使用你的Json -> Json
功能将它们添加到一个地图上?类似的东西:
val withBlock = parse(withoutBlock).extract[List[Clients]] map addBlock
或者我不理解这个问题?
答案 1 :(得分:0)
以下是使用scala.util.parsing.json
import scala.util.parsing.json.JSON
val string =
"""{
| "ClientBase": [
| {
| "string#name": "robert",
| "int#age": 46,
| "string#country": "USA"
| },
| {
| "string#name": "tom",
| "int#age": 45,
| "string#country": "UK"
| }
| ]
|}
""".stripMargin
val start = """"{"ClientBase":[{"""
val end = """}]}"""
val json = JSON.parseFull(string) match {
case Some(e) =>
val clientBase = e.asInstanceOf[Map[String,Any]]
.getOrElse("ClientBase", List[Map[String,Any]]())
val list = clientBase.asInstanceOf[List[Map[String, Any]]]
val result = list.map(e=> e.+("BLOCK_ID" -> "client_base"))
result.mkString(start, ",", end)
case None => string
}
print(json)
//"{"ClientBase":[{Map(string#name -> robert, int#age -> 46.0, string#country -> USA, BLOCK_ID -> client_base),Map(string#name -> tom, int#age -> 45.0, string#country -> UK, BLOCK_ID -> client_base)}]}
希望这是有帮助的。