在Play Framework中将JsObject附加/添加到JsArray中

时间:2015-10-14 17:44:44

标签: json scala playframework playframework-2.3 jsonobject

我是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个值

1 个答案:

答案 0 :(得分:4)

获取空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 ...} ]