使用 json4s 在 scala 中写一个键为 int 到 json 的映射

Write a map with key as int to json in scala using json4s

我正在尝试将 Map 作为 int 写入 json 字符串,但我无法这样做:

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


object MyObject { 
  def main(args: Array[String]) {

  // Works fine
  //val myMap = Map("a" -> List(3,4), "b" -> List(7,8))

  // Does not work
    val myMap = Map(4 -> Map("a" -> 5))

    val jsonString = pretty(render(myMap))

    println(jsonString)

}

我收到以下错误:

[error] /my_stuff/my_file.scala:14: overloaded method value render with alternatives:
[error]   (value: org.json4s.JValue)org.json4s.JValue <and>
[error]   (value: org.json4s.JValue)(implicit formats: org.json4s.Formats)org.json4s.JValue
[error]  cannot be applied to (scala.collection.immutable.Map[Int,scala.collection.immutable.Map[String,Int]])
[error]   val jsonString = pretty(render(myMap))
[error]                           ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

我隐约理解错误信息,看起来 render 需要 JValue 作为输入,而我没有提供,但我也不是第一种情况,代码按我的预期工作。

如何将这样的映射写入 json 字符串?

编辑:我的困惑来源

我主要是 python 程序员,在 python

In [1]: import json

In [2]: wrong = {2: 5}

In [3]: with open("wrong.json") as f:
   ...:     json.dump(wrong, f)

工作得很好,当然 python 将 2.

字符串化

我认为这是一个预期的结果。如果您检查 json specification,您将看到您需要使用字符串作为元素的名称。

所以恐怕你需要这样的东西:

 val myMap = Map("4" -> Map("a" -> 5))