gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:43:10 37 4
gpt4 key购买 nike

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

最佳答案

你得到的错误是因为编译器无法知道 e 的类型引起的。在 Some(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.")
}

关于使用 scala.util.parsing.json 在 Scala 中解析 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21214561/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com