我使用JSON.parseFull
解析Json。
在解析之前,Json就像这样
{
"response":
{
"status":"ok",
"userTier":"developer",
"total":1,
"content":
{
"id":"technology/2014/feb/18/doge-such-questions-very-answered",
"type":"article",
"sectionId":"technology",
"sectionName":"Technology",
"webPublicationDate":"2014-02-18T10:25:30Z",
"webTitle":"What is Doge?",
"webUrl":"https://www.theguardian.com/technology/2014/feb/18/doge-such-questions-very-answered",
"apiUrl":"https://content.guardianapis.com/technology/2014/feb/18/doge-such-questions-very-answered",
"isHosted":false
}
}
}
解析后,它就变成了这个,
Map(response ->
Map(status -> ok,
userTier -> developer,
total -> 1.0,
content ->
Map(webUrl ->
https://www.theguardian.com/technology/2014/feb/18/doge-such-questions-very-answered,
webPublicationDate -> 2014-02-18T10:25:30Z,
webTitle -> What is Doge?,
sectionName -> Technology,
apiUrl -> https://content.guardianapis.com/technology/2014/feb/18/doge-such-questions-very-answered,
id -> technology/2014/feb/18/doge-such-questions-very-answered,
isHosted -> false,
sectionId -> technology,
type -> article
)
)
)
我需要获取像webUrl和webtitle这样的值。
任何人都知道如何实现这一目标?
答案 0 :(得分:0)
Scala Json库有点脆弱,从某种意义上说它并不强烈地键入你解析的Json。因此,我的猜测是在这里和那里放弃asInstanceOf
个电话。以下示例
type JsonMap = Map[String, Any]
val maybeParsedMap: Option[JsonMap] = JSON.parseFull(jsonString).map(_.asInstanceOf[JsonMap])
val content: Option[JsonMap] = for {
parsedMap <- maybeParsedMap
response <- parsedMap.get("response")
content <- response.asInstanceOf[JsonMap].get("content")
} yield content.asInstanceOf[JsonMap]
val webUrl: Option[String] = content.asInstanceOf[JsonMap].get("webUrl").map(_.asInstanceOf[String])