Convert Scala Map to JSON with lift-json


Tested Env: Scala 2.11, lift-json_2.11-2.6.3


1. Normal Scala Map

val m = Map(
"name" -> "john doe",
"age" -> 18,
"hasChild" -> true,
"childs" -> List("a", "b", "c")
view raw Scala1.scala hosted with ❤ by GitHub

m ‘s type: Map[String, Any]

2. Use lift-json’s implicit

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")
view raw Scala2.scala hosted with ❤ by GitHub

Cast Map[String, Any] to Map[String, JValue] explicitly.

3. Convert Map[String, JValue] to JObject

val json = JObject( => JField(x._1, x._2)))
view raw Scala3.scala hosted with ❤ by GitHub

4. Generate String from JObject

// Compact
// Pretty
view raw Scala4.scala hosted with ❤ by GitHub

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.

Leave a Reply