gpt4 book ai didi

scala - 将 JValue 转换为 JSON 字符串

转载 作者:行者123 更新时间:2023-12-03 22:30:24 26 4
gpt4 key购买 nike

我想将 jvalue 转换为 json 字符串。这是我的代码的样子:

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.DefaultFormats._

object Json4sTest {

def main(arg: Array[String]) {
var json = parse("""{"name":"luca", "id": "1q2w3e4r5t", "age": 26, "inner": { "age": 27 }, "url":"http:// www.nosqlnocry.wordpress.com"}""")
// println(json)

val a: List[Map[String, JValue]] = List(Map("inner/age" -> 35, "age" -> 27), Map("name" -> "foo"))
val r = jsonFieldUpdater(json, a)
println(r)

}


def jsonFieldUpdater(json: JValue, list: List[Map[String, JValue]]): JValue =
//
}
}

得到我的结果:
JObject(List((name,JString(foo)), (id,JString(1q2w3e4r5t)), (age,JInt(27)), (inner,JObject(List((age,JInt(35))))), (url,JString(http://    www.nosqlnocry.wordpress.com))))

我正在寻找一个 Json 字符串输出为:
{"name":"luca", "id": "1q2w3e4r5t", "age": 27, "inner": { "age": 35 }, "url":"http://    www.nosqlnocry.wordpress.com"}

最佳答案

如果要打印 JValue 的字符串表示,你可以这样做:println(compact(render(r)))
这样String通过方法接收 compact(render(r))看起来像这样:

{"lotto":{"lotto-id":5,"winning-numbers":[2,45,34,23,7,5,3],"winners":[{"winner-id":23,"numbers":[2,45,34,23,3,5]},{"winner-id":54,"numbers":[52,3,12,11,18,22]}]}}

或者您可以使用 println(pretty(render(r)))获得漂亮 String像这样:
{
"lotto":{
"lotto-id":5,
"winning-numbers":[2,45,34,23,7,5,3],
"winners":[{
"winner-id":23,
"numbers":[2,45,34,23,3,5]
},{
"winner-id":54,
"numbers":[52,3,12,11,18,22]
}]
}
}

使用的示例来自 documentation .

关于scala - 将 JValue 转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42856002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com