【问题标题】:Flatten extranous fields when extracting using LiftJson or Json4s使用 LiftJson 或 Json4s 提取时展平无关字段
【发布时间】:2013-10-10 22:29:12
【问题描述】:

我想使用 LiftJson 或 Json4s 将以下 Json(不完全但类似)提取到以下案例类。

{
  "data": [
    {
    "id": "1234",
    "message": "Test",
    "comments": {
      "data": [
        {
          "id": "4321",
          "content": "Test2",
        }
      ]
    }
}

案例类:

case class A(id: String, message: string, comments: List[B])
case class B(id: String, content: String)

对于我可以做的顶级:(val \ "data").extract[List[A]] 来展平额外的数据字段。但是对于第二级,我看不到直接使用提取的方法。

我可以使用自定义序列化程序(例如here)或以下任何函数(json4s)来删除无关的“数据”字段吗?或者有什么让它变得简单的想法?

def mapField(f: JField => JField): JValue
def transformField(f: PartialFunction[JField, JField]): JValue

我想避免创建其他中间案例类来提取数据,然后用它创建显示的案例类。

【问题讨论】:

  • 您是否尝试过使用transformField 使用JFIeld("data", value) 上的模式匹配,直接返回值?

标签: scala lift-json json4s


【解决方案1】:

我不久前找到了解决方案,但还没有时间回复。我在想,这很容易:

def transformListData(src: JValue, field: String): JValue = {
  src.transformField {
    case JField(x, v) if x == field => JField(field, v \ "data")
  }
}

transformListData(json, "comments")

以下内容将删除多余的 data 并将列表展平。

【讨论】:

    猜你喜欢
    • 2016-10-14
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多