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

4

我有一个 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函数时,编译器会抛出一个错误:“value foreach is not a member of Any”。有人能给我建议吗?如何解析这个json字符串并将其转换为Scala类型。
2个回答

9
你遇到的错误是因为编译器无法确定 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.")
}

谢谢,它正在工作!e.foreach { pair: Tuple2 [String,String] => println(pair._1 + ":" + pair._2) } } - user443426
我使用了相同的模式来捕获解析失败,但编译器返回了以下警告:“非变量类型参数String在类型模式Map [String,String]中未经检查,因为它被擦除”。 - dieHellste

3
您可以按以下方式访问任何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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接