Tested Env: Scala 2.11, lift-json_2.11-2.6.3
1. Normal Scala Map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val m = Map( | |
"name" -> "john doe", | |
"age" -> 18, | |
"hasChild" -> true, | |
"childs" -> List("a", "b", "c") | |
) |
m
‘s type: Map[String, Any]
2. Use lift-json’s implicit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import net.liftweb.json.JsonAST._ | |
import net.liftweb.json.JsonDSL._ | |
import net.liftweb.json.Printer._ | |
val m2: Map[String, JValue] = Map( | |
"name" -> "john doe", | |
"age" -> 18, | |
"hasChild" -> true, | |
"childs" -> List("a", "b", "c") | |
) |
Cast Map[String, Any]
to Map[String, JValue]
explicitly.
3. Convert Map[String, JValue]
to JObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val json = JObject(m2.toList.map(x => JField(x._1, x._2))) |
4. Generate String from JObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Compact | |
compact(render(json)) | |
// Pretty | |
pretty(render(json)) |
5. But!
It cannot convert List that contains Map (List[Map]
), since lift-json
doesn’t have implicit
function for converting Map
to JValue
. I have tried several implicit functions, but all of them failed.
So you need to traverse through List to convert Map
to JValue
(pre-processing), or explicitly convert values by calling implicit
function directly with match
expression.