8

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

1 Answer 1

8

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your valuable answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.