import play.api.libs.json._
import scala.util.parsing.json.{JSON, JSONArray, JSONObject}
我有以下json数组 -
val groupNameList = Json.arr(
Json.obj(
"groupName" -> "All",
"maxSeverity" -> allGroupSeverityCount,
"hostCount" -> (windowsCount + linuxCount + esxCount + networkCount + storageCount + awsLinuxCount + awsWindowsCount)),
Json.obj(
"groupName" -> "Private",
"maxSeverity" -> privateGroupSeverityCount,
"hostCount" -> (windowsCount + linuxCount + esxCount + networkCount + storageCount)),
Json.obj(
"groupName" -> "Public",
"maxSeverity" -> publicGroupSeverityCount,
"hostCount" -> (awsLinuxCount + awsWindowsCount))
)
我想将以下json对象列表附加到此数组 -
List({"groupName" : "group1", "maxSeverity" : 10, "hostCount" : 1, "members" : ["192.168.20.30", "192.168.20.31", "192.168.20.53", "192.168.20.50"]})
我想将列表合并到数组中。
如何使用scala ???
将给定列表附加到json数组答案 0 :(得分:1)
在不同JSON库类型之间转换对象的最简单(尽管可能不是最有效)方法是通过其JSON字符串表示。
(o: JSONObject => Json.parse(o.toString()))
获得List[JsObject]
后,您可以将其传递到JsArray
构造函数,然后使用++
连接两个JsArray
。
将它放在一个例子中:
import play.api.libs.json.{Json, JsArray}
import scala.util.parsing.json.JSONObject
object Foo {
val jsArray = Json.arr(
Json.obj("a" -> "b", "c" -> 2),
Json.obj("d" -> "e", "f" -> 3))
val list = List(
JSONObject(Map("g" -> "h", "i" -> 4)),
JSONObject(Map("j" -> "k", "m" -> 5))
)
def main(args: Array[String]): Unit = {
println(jsArray ++ JsArray(list.map(o => Json.parse(o.toString()))))
// [{"a":"b","c":2},{"d":"e","f":3},{"g":"h","i":4},{"j":"k","m":5}]
}
}