Serializing a scala object into a JSon String using lift-json
12,867
You can "decompose" a case class into JSON and then render it. Example:
scala> import net.liftweb.json.JsonAST._
scala> import net.liftweb.json.Extraction._
scala> import net.liftweb.json.Printer._
scala> implicit val formats = net.liftweb.json.DefaultFormats
scala> case class MyBean(name: String, age: Int)
scala> pretty(render(decompose(MyBean("joe", 35))))
res0: String =
{
"name":"joe",
"age":35
}
But sometimes it is easier to use DSL syntax:
scala> import net.liftweb.json.JsonDSL._
scala> val json = ("name" -> "joe") ~ ("age" -> 35)
scala> pretty(render(json))
res1: String =
{
"name":"joe",
"age":35
}
Author by
Ali Salehi
Updated on June 07, 2022Comments
-
Ali Salehi almost 2 years
I am wondering, would you please let me know how can I use lift-json to serialize a simple bean class into json string (I'm using v2.0-M1). I tried:
val r = JsonDSL.pretty(JsonAST.render(myBean))
and I am getting
[error] found : MyBean [error] required: net.liftweb.json.JsonAST.JValue
-
Martin Konicek about 12 yearsWhat if it's not a case class?
-
ammills01 over 6 yearsWith liftweb 3.1.0 this has moved from pretty(render()) to prettyRender(). You can also do compactRender(). Both are part of net.liftweb.json.JsonAST._