简体   繁体   中英

How to convert Map to Json using Json4s

I am using the json4s library to convert maps in scala to json but keep running into a basic error when operating on Map[Char,Int]:

Here is the code sample that is giving me problems.

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

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

    render(myMap)

error: No implicit view available from (Char, Int) => org.json4s.JsonAST.JValue.

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

The keys of a JSON object are always strings, and furthermore, there is no equivalent of Char in JSON. See json.org for the specification.

You could convert the keys of your Map[Char, Int] before rendering:

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

Also you could consider to use

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

From Scala 2.10

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