我有一个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类型
答案 0 :(得分:6)
您得到的错误是由于编译器无法知道e
模式中Some(e)
的类型,因此它被称为Any
。并且Any
没有foreach
方法。您可以通过将e
的类型明确指定为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.")
}
答案 1 :(得分:2)
您可以在任何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