Convert Scala Map to JSON with lift-json

luca-bravo-24241

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

Ref: https://github.com/lift/lift/blob/master/framework/lift-base/lift-json/src/main/scala/net/liftweb/json/JsonAST.scala#L327

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(m2.toList.map(x => JField(x._1, x._2)))
view raw Scala3.scala hosted with ❤ by GitHub

4. Generate String from JObject

// Compact
compact(render(json))
// Pretty
pretty(render(json))
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