简体   繁体   中英

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

I am trying to write a Map in key as int to json string but I am not able to do so:

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)

}

I am receiving the following error:

[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

I vaguely understand the error message, it looks like render expects JValue as an input, and I am not providing it, but I don't the first case either, and the code works as I expect.

How do I write such map to json string?

Edit: My source of confusion

I am mostly a python programmer, and in python

In [1]: import json

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

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

works perfectly fine, of course python stringifies the 2 .

I think it is an expected result. If you check the json specification you will see that you need to use strings for the names of the elements.

So I am afraid you will need something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM