How to add a json object in to a json array using scala play?
json, playframework, scala
Solution
Remember that `JsArray` is immutable, so writing
jsonArray.+:(emailJson)
will not modify `jsonArray`, it will just create a new json array with `emailJson` appended at the end.
Instead you would need to write something like:
val newArray = jsonArray +: emailJson
and use `newArray` instead of `jsonArray` afterwards.
In your case, you said you need to add an element "at each loop iteration". When using a functional language like Scala, you should probably try to think more in terms of "mapping over collections" rather than "iterating in a loop". For example you could write:
val values = messages map {inboxMessage =>
...
...
Json.obj("fromAddress" -> fromAddressJsonList, "toAddress" -> toAddressJsonList, "ccAddress" -> ccAddressJsonList, "bccAddress" -> bccAddressJsonList, "subject" -> emailMessage.getSubject().toString(), "message" -> Json.toJson(emailMessageBody))
}
val newArray = objects ++ JsArray(values)
Problem
In my scala code i have a json object consisting email data ``` val messages = inboxEmail.getMessages(); var jsonArray = new JsArray for(inboxMessage <- messages) { ... ... val emailJson = Json.obj("fromAddress" -> fromAddressJsonList, "toAddress" -> toAddressJsonList, "ccAddress" -> ccAddressJsonList, "bccAddress" -> bccAddressJsonList, "subject" -> emailMessage.getSubject().toString(), "message" -> Json.toJson(emailMessageBody)) ``` I need to add emailJson to the jsonArray during each loop i tried ``` jsonArray.+:(emailJson) ``` and ``` jsonArray.append(emailJson) ``` but getting empty array What should i use here to add jsonObject into the json array