JSON4Scala从嵌套Object中提取值

时间:2017-08-08 15:34:57

标签: json scala

我正在尝试使用此库https://github.com/momodi/Json4Scala

解析json

我的JSON看起来像这样:

{
  current: {pageviews: 5, time: 50, id: 'jafh784'},
  allTime: {pageviews: 20, time: 438, id: 'adsf6447'}
}

val json = Json.parse(x.getString("user"))
json.asMap("current").asMap("pageviews").asInt

它无法正常工作,我尝试了上述几种组合。我试图使用其他一些库,但它们对我来说更不清楚。 json的架构各不相同,但页面视图始终位于同一位置。我愿意接受其他图书馆的建议。

编辑:我读过有关使用嵌套对象的案例类但是我的所有json中的架构都不准确。我可以只使用案例类,只声明最少的键吗?

1 个答案:

答案 0 :(得分:0)

Play Json允许您在不必指定模型的情况下执行此操作:

import play.api.libs.json._

val raw = """{
  "current": {"pageviews": 5, "time": 50, "id": "jafh784"},
  "allTime": {"pageviews": 20, "time": 438, "id": "adsf6447"}
}"""

val json = Json.parse(raw).as[JsObject]
val currentPageviews = (json \ "current" \ "pageviews").as[Int]

println(currentPageviews) // 5

Here here is a link to a live example

要包含PlayJson依赖项,请将此添加到构建sbt:

libraryDependencies += "com.typesafe.play" % "play-json_2.11" % "2.6.2"

(还有2.12的构建版本)

相关问题