在 Scala 中使用 lift-json 从解析的 JSON 渲染 JSON
这可能是一个简单的问题,而我的困难可能是由于我对 Scala 的陌生(它已经很快成为我最喜欢的语言)。
基本上我有一些如下所示的 JSON:
{
"to" : "Peter",
"from" : "Dave",
"bundle" : [
{"data": [1,2,3,4,5]},
{"data": [2,3,4,5,6]}
]
}
现在,我已经解析了这个 JSON,以便我可以从标头中提取数据(传入和传出),并可以查看包中的各个消息。目前我正在使用这个:
val messages = parsedJSON \\ "bundle" \\ classOf[JObject]
for (m <- messages) println(m)
这给了我:
Map(data -> List(1, 2, 3, 4, 5))
Map(data -> List(2, 3, 4, 5, 6))
但我想在该循环中做的是获取每个地图并将其转换回 JSON 即:
{
"data": [1,2,3,4,5]
}
我已经尝试过 render(m) 和各种其他半随机的东西尝试让它工作,但到目前为止还没有骰子。我最接近的结果给了我这个错误:
No implicit view available from Any => net.liftweb.json.package.JValue.
任何人都可以指出我正确的方向吗?
提前致谢!
This is probably an easy one and my difficulty is likely caused by my newness to Scala (which already is fast becoming my favourite language).
Basically I have some JSON that looks like this:
{
"to" : "Peter",
"from" : "Dave",
"bundle" : [
{"data": [1,2,3,4,5]},
{"data": [2,3,4,5,6]}
]
}
Now, I've parsed this JSON to the point where I can pull the data from the header (to and from) and can look over the individual messages in the bundle. At the moment I'm using this:
val messages = parsedJSON \\ "bundle" \\ classOf[JObject]
for (m <- messages) println(m)
Which gives me:
Map(data -> List(1, 2, 3, 4, 5))
Map(data -> List(2, 3, 4, 5, 6))
But what I want to do in that loop is take each Map and convert it back to JSON i.e.:
{
"data": [1,2,3,4,5]
}
I've tried render(m) and various other semi-random things to try and get it to work but so far no dice. The closest I've come gives me this error:
No implicit view available from Any => net.liftweb.json.package.JValue.
Can anyone please point me in the right direction?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为处理这个问题的最简单方法是为捆绑包创建一个案例类。 Lift-json 可以很好地将数据提取到实例中。然后,您可以循环遍历它们,并通过创建 2 元组将它们隐式转换回 JObject。
I think the easiest way to handle this is to create a case class for a bundle. Lift-json can then nicely extract the data into instances. Then you can just loop through them and turn them back into JObjects implicitly by creating 2-tuples.
如果消息可以是任何数据,您可以将它们提取为 JValue。
if messages can be any data you can extract those as JValues.