gpt4 book ai didi

json - 如何 "flatten"复合对象的 JSon 表示?

转载 作者:行者123 更新时间:2023-12-04 19:18:12 25 4
gpt4 key购买 nike

假设我想在 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  }

最佳答案

使用 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
}

关于json - 如何 "flatten"复合对象的 JSon 表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6822406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com