How to "smooth out" the JSon representation of a composite object?

Suppose I have the following structure that 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 use lift-json "write (...)", but I want to smooth the structure, and instead:

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

I want to receive:

{ id:xx , name:"xxxx" , age:xxxx  }
+5
source share
3 answers

If A and B have multiple fields, you will need a slightly different approach:

import net.liftweb.json._
import net.liftweb.json.JsonAST._
import net.liftweb.json.JsonDSL._

implicit val formats = net.liftweb.json.DefaultFormats
implicit def cToJson(c: C): JValue = (("id" -> c.id):JValue) merge (Extraction decompose c.a) merge (Extraction decompose c.b)
val c1 = C("c1", A("a name", "a nick", "an alias"), B(11, 111, 1111))
Printer pretty (JsonAST render c1)
res0: String =
{
  "id":"c1",
  "name":"a name",
  "nick":"a nick",
  "alias":"an alias",
  "age":11,
  "weight":111,
  "height":1111
}
+1
source

Use the method transformon 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
}
+4
source

D (id, name, age) , json. , .

0

All Articles