Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

scala

lift

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
like image 692
Ali Salehi Avatar asked Feb 08 '10 16:02

Ali Salehi


1 Answers

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
}
like image 50
Joni Avatar answered Oct 28 '22 14:10

Joni