简体   繁体   中英

How to convert nested maps of type Map[String, Map[String, Any]] to JSON in Scala?

I tried converting Map[String, Map[String, Any]] in Scala to JSON but since they have nested maps so unable to do it. Is there a way to do it? I tried looking at this link but it converts everything to string and converts a list as "List(...)". Any ideas how to go about this? I am even fine with solutions of Map[String, Map[String, String]].

You can use play-json library . Then converting nested maps would look like this:

import play.api.libs.json.{JsValue, Json}

val nestedMap: Map[String, Map[String, String]] = Map("employees" -> Map("Paul" -> "developer", "Alice" -> "accountant"))
val json: JsValue = Json.toJson(nestedMap)
val compactJson: String = Json.stringify(json)

println(compactJson)

Output:

{"employees":{"Paul":"developer","Alice":"accountant"}}

Thanks. I also saw that one can do compact(render(decompose(nestedMap))). Here I am talking about the netliftweb.json library

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