[英]update json string in scala using jackson
I have a json我有一个 json
val nodeJson =
s"""
{
"NAME":"node1",
"CONFIG":{
"colMap": {
"idcols": [
],
"emailcols":[
]
},
"col.partitions": "3"
}
}
"""
I have to populate "idcols" and "emailcols" array dynamically from scala array.我必须从 scala 数组动态填充“idcols”和“emailcols”数组。
like if i have arrays:就像我有 arrays 一样:
val idcols = Array("per_id","dep_id")
val emailcols = Array("per_email","dep_email")
then these values need to set in the json string那么这些值需要在 json 字符串中设置
I have to use com.fasterxml.jackson
library.我必须使用
com.fasterxml.jackson
库。
I am able to get the arrays:我能够得到 arrays:
val obj = new ObjectMapper()
val root = obj.readTree(nodeJson)
val value = root.get("CONFIG").get("colMap")
println(value)
But I am not sure how to update it and set it back to the json.但我不确定如何更新它并将其设置回 json。 Kinldy let me know how can i update the json string.
Kinldy 让我知道如何更新 json 字符串。
When using jackson you most mutators are not defined on JsonNode
but rather the specific sub-classes for that type of node (in your case ArrayNode
for json arrays)使用 jackson 时,大多数突变器都没有在
JsonNode
上定义,而是在该类型节点的特定子类上定义(在您的情况下ArrayNode
用于 json 数组)
For example to add a string to the idCols
array you would:例如,要将字符串添加到
idCols
数组,您可以:
root.get("CONFIG").get("colMap").get("idCols").asInstanceOf[ArrayNode].add("someArbitraryString")
If you prefer more type safety (at the performance cost of allocating an extra case class) you could also consider creating a case class matching the structure of your document, parsing the json into that, updating the scala case class and serializing back to a json string. If you prefer more type safety (at the performance cost of allocating an extra case class) you could also consider creating a case class matching the structure of your document, parsing the json into that, updating the scala case class and serializing back to a json细绳。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.