开发者

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

开发者 https://www.devze.com 2023-03-23 00:15 出处:网络
Suppose I have the following structure I want to serialize in Json: case class A(name:String) case class B(age:Int)

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(...)" 开发者_StackOverflow中文版, 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  }


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
}


If A and B have multiple fields you will want 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
}


You can declare a new object D with fields (id, name, age) and load the values you want in the constructor then serialize that class to json. There may be another way but this way will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消