Json使用scala.util.parsing.json在Scala中解析

时间:2014-01-19 08:15:38

标签: json scala

我有一个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类型

2 个答案:

答案 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