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
You need to load the file, then parse it using var val = JSON. parse(textFromFile) you can then use push to push it onto the end of that val val. push({/*new object*/}) , then you will need to stringify the val var newString = JSON. strigify(val) and then you finally can save newString to a file.
You use the JSValue class to convert basic values, such as numbers and strings, between JavaScript and Objective-C or Swift representations to pass data between native code and JavaScript code.
Argonaut is a great library. It's by far the best JSON library for Scala, and the best JSON library on the JVM. If you're doing anything with JSON in Scala, you should be using Argonaut. circe is a fork of Argonaut with a few important differences.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With