【问题标题】:Write a map with key as int to json in scala using json4s使用 json4s 在 scala 中将键作为 int 的映射写入 json
【发布时间】:2015-05-15 14:39:10
【问题描述】:

我正在尝试将 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 scala json4s


    【解决方案1】:

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

    所以恐怕你需要类似的东西:

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

    【讨论】:

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