Spark Scala - How to construct Scala Map from nested JSON?

醉酒当歌 提交于 2019-12-02 08:25:29

You can do it using the below sample code

import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods.parse



  case class AirPortScores(airport: String, score: Double)
  case class JsonRulesHandler(airports: List[AirPortScores])

  val jsonString: String = """{"airports":[{"airport":"sfo","score":1},{"airport":"phx","score":1},{"airport":"sjc","score":1}]}"""

  def loadJsonString(JsonString: String): JsonRulesHandler = {
  implicit val formats: DefaultFormats.type = org.json4s.DefaultFormats
  parse(JsonString).extract[JsonRulesHandler]
}

val parsedJson: JsonRulesHandler = loadJsonString(jsonString)
parsedJson.airports.foreach(println)//you can select parsedJson.airport or scores
//below ouput
AirPortScores(sfo,1.0)
AirPortScores(phx,1.0)
AirPortScores(sjc,1.0)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!