我是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
个值
答案 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 ...} ]