Sakalya Sakalya - 18 days ago 6
Scala Question

Converting to net.liftweb.json.JsonAST.JObject Lift in Scala

I am trying to construct a JSON object from a list where key is "products" and value is List[Product] where Product is a case class.But I am getting error that says "type mismatch; found : (String, List[com.mycompnay.ws.client.Product]) required: net.liftweb.json.JObject (which expands to) net.liftweb.json.JsonAST.JObject".

What I have done so far is as below:

val resultJson:JObject = "products" -> resultList
println(compact(render(resultJson)))

Answer

You're looking for decompose (doc). See this answer.

I tested the following code and it worked fine:

import net.liftweb.json._
import net.liftweb.json.JsonDSL._
import net.liftweb.json.Extraction._

implicit val formats = net.liftweb.json.DefaultFormats

case class Product(foo: String)

val resultList: List[Product] = List(Product("bar"), Product("baz"))
val resultJson: JObject = ("products" -> decompose(resultList))
println(compact(render(resultJson)))

Result:

{"products":[{"foo":"bar"},{"foo":"baz"}]}