[英]How to add a json object in to a json array using scala play?
在我的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))
我需要在每個循環期間將emailJson添加到jsonArray
我試過了
jsonArray.+:(emailJson)
和
jsonArray.append(emailJson)
但得到空陣列
我應該在這里使用jsonObject添加到json數組中
請記住, JsArray
是不可變的,所以寫作
jsonArray.+:(emailJson)
不會修改jsonArray
,它只是創建一個新的json數組, emailJson
附加了emailJson
。
相反,你需要寫一些像:
val newArray = jsonArray +: emailJson
然后使用newArray
而不是jsonArray
。
在你的情況下,你說你需要在“每次循環迭代”中添加一個元素。 當使用像Scala這樣的函數式語言時,您應該嘗試在“映射集合”而不是“循環迭代”方面考慮更多。 例如,您可以寫:
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.