我可以使用Scala lift-json库将JSON解析为Map吗? [英] Can I use the Scala lift-json library to parse a JSON into a Map?

查看:101
本文介绍了我可以使用Scala lift-json库将JSON解析为Map吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使用lift-json库的JObject类充当地图?

Is there a way to use the lift-json library's JObject class to act like a Map?

例如:

val json = """
{ "_id" : { "$oid" : "4ca63596ae65a71dd376938e"} , "foo" : "bar" , "size" : 5}
"""

val record = JsonParser.parse(json)
record: net.liftweb.json.JsonAST.JValue = JObject(List(JField(_id,JObject(List(JField($oid,JString(4ca63596ae65a71dd376938e))))), JField(foo,JString(bar)), JField(size,JInt(5))))

</code>

我本来希望record("foo")返回"bar"

I would have expected record("foo") to return "bar"

我注意到一个值函数,它打印出一个Map,但实际对象是JValue.this.Values?

I noticed a values function and it prints out a Map but the actual object is a JValue.this.Values?

scala> record.values res43: record.Values = Map((_id,Map($oid -> 4ca63596ae65a71dd376938e)), (foo,bar), (size,5))

scala> record.values res43: record.Values = Map((_id,Map($oid -> 4ca63596ae65a71dd376938e)), (foo,bar), (size,5))

scala> record.values("foo") :12: error: record.values of type record.Values does not take parameters record.values("foo")

scala> record.values("foo") :12: error: record.values of type record.Values does not take parameters record.values("foo")

有一些示例,其中lift-json库提取了一个case类,但是在这种情况下,我事先不知道json模式.

There are examples with the lift-json library extracting a case class but in this case, I don't know the json schema in advance.

推荐答案

如果您查看实现,将会看到

If you look at the implementation, you'll see

case class JObject(obj: List[JField]) extends JValue {
  type Values = Map[String, Any]
  def values = Map() ++ obj.map(_.values.asInstanceOf[(String, Any)]) // FIXME compiler fails if cast is removed
}

所以这应该起作用:

record.values.asInstanceOf[Map[String, Any]]("foo")

您也可以尝试

record.values.apply("foo")

这篇关于我可以使用Scala lift-json库将JSON解析为Map吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆