簡體   English   中英

如何使用scala play將json對象添加到json數組中?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM