【问题标题】:json4s - Ignore field of particular type during serializationjson4s - 在序列化期间忽略特定类型的字段
【发布时间】:2016-03-31 12:19:40
【问题描述】:

假设我有一些标记trait Ignore 我希望在序列化过程中忽略所有标记有此特征的字段。

所以如果我有课

case class A(a: Int) extends Ignore
case class B(f: String, a: A, d: Int)

序列化后 B 的 json 不应包含 a 字段。

注意:我知道有机会按名称忽略字段,但这不是我需要的。

【问题讨论】:

    标签: scala json4s


    【解决方案1】:

    您可以使用CustomSerializer。 您可以通过提供一个空的 PartialFunction 作为反序列化器来仅自定义序列化:

    trait Ignore
    case class A(a: Int) extends Ignore
    case class B(f: String, a: A, d: Int)
    
    implicit val formats = DefaultFormats +
      new CustomSerializer[Ignore](formats => (
      PartialFunction.empty,
      { case _: Ignore => JNothing }
      ))
    
    // prints "{"f":"x","d":2}"
    println(Serialization.write(B("x", A(1), 2)))
    // deserializes to B(x,A(1),2)
    println(Serialization.read[B]("""{"f":"x","a":{"a":1},"d":2}"""))
    

    编辑:在撰写本文时 (3.3.0) json4s-native 有一个错误,如果 first 字段被忽略(例如 case class B(a: A, ...).I建议使用 json4s-jackson 直到问题解决

    首先使用Extraction.decompose,然后使用Serialization 似乎可以解决问题:

    trait Ignore
    case class A(a: Int) extends Ignore
    case class B(a: A, d: Int)
    
    implicit val formats = DefaultFormats +
      new CustomSerializer[Ignore](formats => (
        PartialFunction.empty,
        { case _: Ignore => JNothing }
        ))
    
    // prints {,"d":2}
    println(Serialization.write(B(A(1), 2)))
    // prints {"d":2}
    println(Serialization.write(Extraction.decompose(B(A(1), 2))))
    

    【讨论】:

    • 是的,这行得通,但是如果我在 B 字段的开头放置一个字段,它会产生无效的 json。例如:case class B(a: A, d: Int) 产生 "{,"d":2}" 如何解决?
    • @maks 它对我有用:{"d":2}。您使用的是旧的 json4s 版本吗?我在 3.3.0
    • @maks 好的,我还没有检查,但我认为我的代码有效,因为我使用的是 json4s-jackson。你用的是原生的吗?
    • @maks 已确认,这是一个 json4s 问题。这绝对是一个bug,我会在github上开一个issue,我建议还是用jackson,因为它更快
    • @maks 我找到了一种解决方法,但是您必须更改序列化代码,直到(如果有的话)错误得到解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2015-01-27
    相关资源
    最近更新 更多