假設我有以下簡單的JSON字符串:是否有簡單的方法/方法從斯卡拉json中提取元素?
val jsonString="""{
| "result": {
| "header": ["time-stamp", "id-number", "call-number", "trial-number", "ratio"],
| "data": [
| ["2017-08-29 00:00:00", "111550", "16", "10", "0.79"],
| ["2017-08-29 00:00:00", "111551", "15", "18", "0.55"],
| ["2017-08-29 00:00:00", "111552", "13", "16", "0.35"]
| ],
| "paging": { "a": 5, "b": 10, "c": 11}
| }
|}""".stripMargin
現在我想提取以下表格的data
:
//List[List[String]]
List(
List("2017-08-29 00:00:00", "111550", "16", "10", "0.79"),
List("2017-08-29 00:00:00", "111551", "15", "18", "0.55"),
List("2017-08-29 00:00:00", "111552", "13", "16", "0.35")
)
我的審判:
scala> import play.api.libs.json._
scala> val json=Json.parse(jsonString)
scala> val jsonTransformer = (__ \ 'result \ 'data).json.pick[JsArray]
scala> val dataArray = json.transform(jsonTransformer).get
//dataArray: json.JsArray = [["2017-08-29 00:00:00","111550","16","10","0.79"], ["2017-08-29 00:00:00","111551","15","18","0.55"], ["2017-08-29 00:00:00","111552","13","16","0.35"]]
scala> val data = dataArray.value.map(_.as[JsArray]).map(_.value).toList.map(_.toList)
//data: List[List[json.JsValue]] = List(List("2017-08-29 00:00:00", "111550", "16", "10", "0.79"), List("2017-08-29 00:00:00", "111551", "15", "18", "0.55"), List("2017-08-29 00:00:00", "111552", "13", "16", "0.35"))
根據REPL值,我知道data
的類型是List[List[json.JsValue]]
,而不是List[List[String]]
。
所以我想知道如何以簡單的方式處理問題。衷心感謝!
優雅的方式:)非常感謝。 – xyz