I have a 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.
like if i have 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
I have to use com.fasterxml.jackson
library.
I am able to get the 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. Kinldy let me know how can i update the json string.
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)
For example to add a string to the idCols
array you would:
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.