Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to "flatten" the JSon representation of a composite object?

Tags:

json

scala

lift

Suppose I have the following structure I want to serialize in Json:

case class A(name:String)

case class B(age:Int)

case class C(id:String, a:A,b:B)

I'm using lift-json "write(...)" , but I want to flatten the structure so instead of:

{ id:xx , a:{ name:"xxxx" }, b:{ age:xxxx } }

I want to get:

{ id:xx , name:"xxxx" , age:xxxx  }
like image 321
GClaramunt Avatar asked Jul 25 '11 21:07

GClaramunt


1 Answers

Use transform method on JValue:

import net.liftweb.json._
import net.liftweb.json.JsonAST._
implicit val formats = net.liftweb.json.DefaultFormats
val c1 = C("c1", A("some-name"), B(42))
val c1flat = Extraction decompose c1 transform  { case JField(x, JObject(List(jf))) if x == "a" || x == "b" => jf }
val c1str = Printer pretty (JsonAST render c1flat)

Result:

c1str: String =
{
  "id":"c1",
  "name":"some-name",
  "age":42
}
like image 125
romusz Avatar answered Sep 19 '22 14:09

romusz