Mamaf
Mamaf

Reputation: 360

How to add element into a nested array using json4s with Scala

I have the following json String:

  val jsonMessage: String =
    """{
      | "code": "OK",
      | "idEvent": "123",
      | "contract": {
      |     "idApplication": "001"
      | },
      | "version": {
      |     "idVersion": "1",
      |     "entity": [{
      |       "idEntity": "5",
      |       "entityType": [{
      |         "entityNumber": "147",
      |           "entityVersion": [{
      |             "entityCode": "A",
      |             "idCode": "753"
      |           }]
      |       }]
      |     }]
      | }
      |}""".stripMargin

I would like to position a new name field within the entityVersion array using json4s. Any idea how to do this in Scala ?

Upvotes: 0

Views: 52

Answers (1)

Saeid Dadkhah
Saeid Dadkhah

Reputation: 363

You can use this code snippet:

val root = JsonMethods.parse(jsonMessage)
root.transformField {
  case ("entityVersion", JArray(list)) =>
    val updatedObjects = list.map { case obj: JObject =>
      JObject(obj.obj :+ ("name", JString("Name Value")))
    }
    ("entityVersion", JArray(updatedObjects))
}

Upvotes: 1

Related Questions