json - 为什么这个 json4s 代码在 scala repl 中工作但无法编译?

标签 json scala json4s scala-2.11

我正在将类似 json 的字符串转换为 json,以下代码在 scala repl 中有效

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.JsonDSL.WithDouble._
import org.json4s.native.JsonMethods._

val value = "{100:1.50;500:1.00;1000:0.50}"

val data = value.stripPrefix("{").stripSuffix("}").split(";").map(a => {
  val b = a.split(":")
  (b(0),b(1))
}).toMap
compact(render(data))

编译时出现如下错误

[error] ... type mismatch;
[error]  found   : scala.collection.immutable.Map[String,String]
[error]  required: org.json4s.JValue
[error]     (which expands to)  org.json4s.JsonAST.JValue
[error]       compact(render(data))
[error]                      ^

这是为什么,我该如何解决?

我怀疑类型系统有问题。

最佳答案

render()JsonMethods._ 导入,它实际上需要一个 JValue。您已导入隐式 map2jvalue来自这两个导入 import org.json4s.JsonDSL._import org.json4s.JsonDSL.WithDouble._ 的两次。

我怀疑编译器由于不明确的导入而没有找到隐含的,尝试更具选择性:the 3rd import seems redundant (带有 JsonDSL.WithDouble._ 的那个)。

有时您可以使用 -Xlog-implicits 运行 scalac 以查看为什么不使用隐式。

关于json - 为什么这个 json4s 代码在 scala repl 中工作但无法编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138331/

相关文章:

scala - 为什么在这个 Scala 代码中需要向上转换?

json - 使用 json4s 将 scala 对象转换为 json

scala - `JObject(rec) <- someJArray` 在理解中意味着什么

javascript - json 选择一个名为 "item"的项目

javascript - 在 AngularJS 中的下拉列表中显示 JSON 数据

java - 如何将json解析为对象

java - org.json.JSONException : End of input at character 0

java - 在 sbt 中强制执行 Scala 项目的 Java 版本?

scala - Spark 多个数据帧保存

json - 如何使用 scala 中的 json4s 库测试我为解析器创建的案例类是否正确?