[英]How to create json string from scala ArrayBuffer
我从 for 循环内部创建了一个 ArrayBuffer。 现在我想用同一个 ArrayBuffer 创建 json 字符串
下面的代码我用来创建数组缓冲区val res=new ArrayBuffer[ArrayBuffer[_>:Any]]
`df =
+---+---+
| _1| _2|
+---+---+
| 1| 5|
| 2| 57|
+---+---+
df.collect.foreach(x=> {
res += ArrayBuffer(x(0), x(1))
})
需要低于 json 字符串从 ArrayBuffer 上方动态而不低于硬编码的数组值
val str = "head"
val cur = """{"%s":{"%s":"%s","%s":"%s"}}""".format(str,res(0)(0),res(0)(1),res(1)(0),res(1)(1))
预期的 Output 应低于基于 ArrayBuffer 大小的动态。 列将为 2,但行数可以增加或减少。
Array Buffer is like this --> ArrayBuffer(ArrayBuffer(1, 5), ArrayBuffer(2, 57))
预期 Json
{"head":{"1":"5","2":"57"}}
我建议你使用 Json 序列化器。 对我来说最简单的是play-json。
您可以像这样将它添加到您的 sbt 中:
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2"
https://mvnrepository.com/artifact/com.typesafe.play/play-json
然后很简单
// convert to a list of tuple
val body: ArrayBuffer[(String, JsValue)] = res.map(e => (e.head.toString, Json.toJson(e(1))))
print(Json.toJson(Json.obj({"head" -> JsObject(list)})))
这里还有更多示例: https://www.playframework.com/documentation/2.8.x/ScalaJson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.