【问题标题】:How to convert Map to Json using Json4s如何使用 Json4s 将 Map 转换为 Json
【发布时间】:2014-06-09 08:38:02
【问题描述】:

我正在使用 json4s 库将 scala 中的地图转换为 json,但在 Map[Char,Int] 上操作时一直遇到基本错误:

这是给我带来问题的代码示例。

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

    val myMap = Map('a' -> 123)

    render(myMap)

错误:(Char, Int) => org.json4s.JsonAST.JValue 没有可用的隐式视图。

问题:使用 Json4s 将由 [Char, Int] 组成的 Map 转换为 Json 对象的正确方法是什么?

【问题讨论】:

    标签: json scala json4s


    【解决方案1】:

    JSON 对象的键始终是字符串,此外,JSON 中没有 Char 等价物。有关规范,请参阅json.org

    您可以在渲染之前转换Map[Char, Int] 的键:

    myMap.map { case(k, v) => (k.toString, v) }
    

    【讨论】:

      【解决方案2】:

      你也可以考虑使用

      ``println(scala.util.parsing.json.JSONObject(m))```

      来自 Scala 2.10

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多