2017-09-02 69 views
0

假設我有以下簡單的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]]

所以我想知道如何以簡單的方式處理問題。衷心感謝!

回答

1

我想你需要投String另

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

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

享受!

+0

優雅的方式:)非常感謝。 – xyz

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]]] 
3
(Json.parse(jsonString) \ "result" \ "data").as[List[List[String]]]