json - 如何使用Json4s将Map转Json

标签 json scala json4s

我正在使用 json4s 库将 scala 中的 map 转换为 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 中没有可用的隐式 View 。

Question: What is the correct way to convert a Map that is made of [Char, Int] to a Json object using Json4s?

最佳答案

JSON 对象的键总是字符串,而且在 JSON 中没有 Char 的等价物。参见 json.org用于规范。

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

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

关于json - 如何使用Json4s将Map转Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116536/

相关文章:

java - 使用 GSon 从 JSon 转换为多个未知的 java 对象类型

Java 数组与 Scala 数组

java - Scala中获取Json头节点值

python - 使用 Python 在 Postgresql 中存储 Json 对象数组

android - 在 Android ListView 中显示来自 Json String 的数据

javascript - 将 1 的 JSON 数组转换为对象

scala - 使用带有严格 Unmarshaller 的 akka-http 客户端 `entity.discardEntityBytes`

Scala:如何设置在抽象父类(super class)构造函数中定义的实例字段?

scala - json4s - 如何使用多个 FieldSerializer

scala - 使用 Scala 和 JSON4S 操作 JSON 中的数组