如何“展平”复合对象的JSon表示?

时间:2011-07-25 21:10:21

标签: json scala lift

假设我想要在Json中序列化以下结构:

case class A(name:String)

case class B(age:Int)

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

我正在使用lift-json“write(...)”,但我希望将结构展平,而不是:

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

我想得到:

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

3 个答案:

答案 0 :(得分:4)

transform上使用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)

结果:

c1str: String =
{
  "id":"c1",
  "name":"some-name",
  "age":42
}

答案 1 :(得分:1)

如果A和B有多个字段,您需要稍微不同的方法:

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
}

答案 2 :(得分:0)

您可以使用字段(id,name,age)声明一个新对象D,并在构造函数中加载所需的值,然后将该类序列化为json。可能有另一种方式,但这种方式可行。