如何使用标准Scala类在Scala中解析JSON?

我正在使用Scala 2.8中的JSON类中的构建来解析JSON代码。由于最小化依赖性,我不想使用Liftweb之一。


我这样做的方法似乎势在必行,是否有更好的方法可以做到?


import scala.util.parsing.json._

...

val json:Option[Any] = JSON.parseFull(jsonString)

val map:Map[String,Any] = json.get.asInstanceOf[Map[String, Any]]

val languages:List[Any] = map.get("languages").get.asInstanceOf[List[Any]]

languages.foreach( langMap => {

val language:Map[String,Any] = langMap.asInstanceOf[Map[String,Any]]

val name:String = language.get("name").get.asInstanceOf[String]

val isActive:Boolean = language.get("is_active").get.asInstanceOf[Boolean]

val completeness:Double = language.get("completeness").get.asInstanceOf[Double]

}


墨色风雨
浏览 1189回答 3
3回答

白板的微信

这是一个基于提取器的解决方案,它将进行类转换:class CC[T] { def unapply(a:Any):Option[T] = Some(a.asInstanceOf[T]) }object M extends CC[Map[String, Any]]object L extends CC[List[Any]]object S extends CC[String]object D extends CC[Double]object B extends CC[Boolean]val jsonString =&nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "languages": [{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name": "English",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "is_active": true,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "completeness": 2.5&nbsp; &nbsp; &nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name": "Latin",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "is_active": false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "completeness": 0.9&nbsp; &nbsp; &nbsp; &nbsp; }]&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; """.stripMarginval result = for {&nbsp; &nbsp; Some(M(map)) <- List(JSON.parseFull(jsonString))&nbsp; &nbsp; L(languages) = map("languages")&nbsp; &nbsp; M(language) <- languages&nbsp; &nbsp; S(name) = language("name")&nbsp; &nbsp; B(active) = language("is_active")&nbsp; &nbsp; D(completeness) = language("completeness")} yield {&nbsp; &nbsp; (name, active, completeness)}assert( result == List(("English",true,2.5), ("Latin",false,0.9)))在for循环的开始,我人为地将结果包装在一个列表中,以便在最后生成一个列表。然后在for循环的其余部分中,我将使用生成器(使用<-)和值定义(使用=)将利用unapply方法的事实。(较旧的答案已被删除-如果您感到好奇,请检查编辑历史记录)

qq_笑_17

这是我进行模式匹配的方式:val result = JSON.parseFull(jsonStr)result match {&nbsp; // Matches if jsonStr is valid JSON and represents a Map of Strings to Any&nbsp; case Some(map: Map[String, Any]) => println(map)&nbsp; case None => println("Parsing failed")&nbsp; case other => println("Unknown data structure: " + other)}
打开App,查看更多内容
随时随地看视频慕课网APP