[英]How to add a json object in to a json array using scala play?
In my scala code i have a json object consisting email data 在我的scala代码中,我有一个包含电子邮件数据的json对象
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 我需要在每个循环期间将emailJson添加到jsonArray
i tried 我试过了
jsonArray.+:(emailJson)
and 和
jsonArray.append(emailJson)
but getting empty array 但得到空阵列
What should i use here to add jsonObject into the json array 我应该在这里使用jsonObject添加到json数组中
Remember that JsArray
is immutable, so writing 请记住, JsArray
是不可变的,所以写作
jsonArray.+:(emailJson)
will not modify jsonArray
, it will just create a new json array with emailJson
appended at the end. 不会修改jsonArray
,它只是创建一个新的json数组, emailJson
附加了emailJson
。
Instead you would need to write something like: 相反,你需要写一些像:
val newArray = jsonArray +: emailJson
and use newArray
instead of jsonArray
afterwards. 然后使用newArray
而不是jsonArray
。
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". 当使用像Scala这样的函数式语言时,您应该尝试在“映射集合”而不是“循环迭代”方面考虑更多。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.