是否有简单的方法/方法从scala中的json中提取元素?

时间:2017-09-02 16:57:35

标签: json scala playframework

假设我有以下简单的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]]

所以我想知道如何以简单的方式处理问题。真诚的谢谢!

3 个答案:

答案 0 :(得分:3)

使用杰克逊图书馆

scala> import org.json4s.jackson.JsonMethods
scala> val parsedMap = JsonMethods.parse(jsonString).values.asInstanceOf[Map[String, Any]].head._2.asInstanceOf[Map[String,Any]]
scala> parsedMap.get("data").get.asInstanceOf[List[List[String]]]

答案 1 :(得分:3)

(Json.parse(jsonString) \ "result" \ "data").as[List[List[String]]]

答案 2 :(得分:1)

我认为你还需要演员阵容

val data = dataArray.value
 .map(_.as[JsArray])
 .map(_.value)
 .map(_.toList.map(_.as[String]))
 .toList

val data = dataArray.as[List[List[String]]]

享受!