Append/Add JsObject 到 Play Framework 中的 JsArray

Append/Add JsObject into JsArray in Play Framework

我是 Play Framework 的新手,我需要将 append/add JsObject 元素转换为 JsArray

瞄准(我需要的)

 {"s_no":1,"s_name":"one",
    ,"sub_s":  [{"sub_s_no":1,"sub_s_name":"one_sub","sub_s_desc":"one_sub"},{"sub_s_no":2,"sub_s_name":"two_sub","sub_s_desc":"two_sub"}]},
{"s_no":2,"s_name":"two","sub_s":[{"sub_s_no":2,"sub_s_name":"two_sub","sub_s_desc":"two_sub"},
    {"sub_s_no":3,"sub_s_name":"three_sub","sub_s_desc":"three_sub"}]}

我得到了什么

JsObject 1

{"s_no":1,"s_name":"one",
,"sub_s":[{"sub_s_no":1,"sub_s_name":"one_sub","sub_s_desc":"one_sub"},{"sub_s_no":2,"sub_s_name":"two_sub","sub_s_desc":"two_sub"}]}

JsObject 2

{"s_no":2,"s_name":"two","sub_s":[{"sub_s_no":2,"sub_s_name":"two_sub","sub_s_desc":"two_sub"},
{"sub_s_no":3,"sub_s_name":"three_sub","sub_s_desc":"three_sub"}]}

我有两个JsObject并且会得到两个以上,我需要add/append这些都JsObjects变成JsArray

我尝试使用 .+:.append 方法,但给出了空的 JsArray

之所以得到一个空的JsArray是因为JsArray是不可变的,所以原来的JsArray不会被修改。您需要分配追加的结果到一个新变量,以便它按您期望的方式工作。

val jsonString1 = """{"s_no":1,"sub_s":[1,2]}"""
val jsonString2 = """{"s_no":2,"sub_s":[3,4]}"""

val jsObj1 = Json.parse(jsonString1)
val jsObj2 = Json.parse(jsonString2)

val emptyArray = Json.arr()
val filledArray = emptyArray :+ obj1 :+ obj2

Json.prettyPrint(emptyArray)
Json.prettyPrint(filledArray)

以及一些 REPL 输出

> filledArray: play.api.libs.json.JsArray = [{"s_no":1,"s_name":"one","sub_s":[{"sub_s_no":1,"sub_s_name":"one_sub","sub_s_desc":"one_sub"},{"sub_s_no":2,"sub_s_name":"two_sub","sub_s_desc":"two_sub"}]},{"s_no":2,"s_name":"two","sub_s":[{"sub_s_no":2,"sub_s_name":"two_sub","sub_s_desc":"two_sub"},{"sub_s_no":3,"sub_s_name":"three_sub","sub_s_desc":"three_sub"}]}]
> // pretty print of the empty array
> res1: String = [ ]
> // pretty print of the filled array
> res2: String = [ {"s_no" : 1 ...}, {"s_no" : 2 ...} ]