[英]Json parsing in Scala with scala.util.parsing.json
我有一个json对象"{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}"
和代码:
println(request.getParameter("content"))//{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}
val result = scala.util.parsing.json.JSON.parseFull(request.getParameter("content"))
result match {
case Some(e) => { println(e); //output: Map(name -> OZKA, monthRevenue -> 1000.75, developer -> true, birthDate -> 1981-02-08T20:00:00.000Z, id -> 1.0)
e.foreach((key: Any, value: Any) => {println(key + ":" + value)})
}
case None => println("Failed.")
}
,当我尝试调用map或foreach函数时,编译器将引发错误“ foreach值不是Any的成员”。 有人可以建议我一种方式,如何解析此json字符串并将其转换为Scala类型。
您得到的错误是由于编译器无法知道Some(e)
模式中e
的类型而导致的,将其推断为Any
。 而且Any
没有foreach
方法。 您可以通过将e
的类型显式指定为Map
来解决此问题。
其次,对于Map foreach
,其签名为foreach(f: ((A, B)) ⇒ Unit): Unit
。 匿名函数的参数是一个包含键和值的元组。
尝试这样的事情:
println(request.getParameter("content"))//{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}
val result = scala.util.parsing.json.JSON.parseFull(request.getParameter("content"))
result match {
case Some(e:Map[String,String]) => {
println(e); //output: Map(name -> OZKA, monthRevenue -> 1000.75, developer -> true, birthDate -> 1981-02-08T20:00:00.000Z, id -> 1.0)
e.foreach { pair =>
println(pair._1 + ":" + pair._2)
}
}
case None => println("Failed.")
}
您可以按以下方式访问任何json中的键和值:
import scala.util.parsing.json.JSON
import scala.collection.immutable.Map
val jsonMap = JSON.parseFull(response).getOrElse(0).asInstanceOf[Map[String,String]]
val innerMap = jsonMap("result").asInstanceOf[Map[String,String]]
innerMap.keys //will give keys
innerMap("anykey") //will give value for any key anykey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.