Can I use the Scala lift-json library to parse a JSON into a Map?

寵の児 提交于 2019-12-03 11:12:43

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
}

So this should work:

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

You could also try

record.values.apply("foo")

JValue.Values is a path dependent type. Meaning that if you hold on a JString it will be a String, or if you got a JArray it will be a List[Any]. If you are sure that the JSON you parse is a JSON object you can cast it to a proper type.

val record = JsonParser.parse(json).asInstanceOf[JObject]

A path dependent type for JObject is a Map[String, Any], thus:

scala> record.values("foo")                                     
res0: Any = bar

Just of curiosity, isn't it a bit problematic if you do not know the shape of data you are going to parse?

Note, if your data contains (name, description, age) and the age is optional you can read that JSON into:

case class Person(name: String, description: String, age: Option[Int])
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!