Ali Salehi
Ali Salehi

Reputation: 6999

Serializing a scala object into a JSon String using lift-json

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

Upvotes: 22

Views: 13639

Answers (1)

Joni
Joni

Reputation: 2789

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
}

Upvotes: 30

Related Questions