【问题标题】:How do I serialize one field "preservingEmptyValues" to null using json4s如何使用 json4s 将一个字段“preservingEmptyValues”序列化为空
【发布时间】:2018-04-10 15:52:17
【问题描述】:

我正在使用 json4s。

我知道您可以使用 DefaultFormats.preservingEmptyValues 在一个类型中“保留所有 Option 成员的 None 值”。

输出如下:

斯卡拉

case class MyType(a: Option[String], b: Option[Int], c: Int)

实例

MyType(None, None, 1)

输出

{ "a": null , "b": null , "c": 1 }


没有DefaultFormats.preservingEmptyValues 的输出是这样的:

斯卡拉

case class MyType(a: Option[String], b: Option[Int], c: Int)

实例

MyType(None, None, 1)

输出

{ "c": 1 }

我想做的是,它为一个成员保留默认行为(删除属性),比如a,并为另一个成员使用preservingEmptyValues,比如b,并有如下输出:

斯卡拉

case class MyType(a: Option[String], b: Option[Int], c: Int)

实例

MyType(None, None, 1)

输出

{ "b": null , "c": 1 }


如何使用 json4s 实现这一目标?

【问题讨论】:

    标签: json scala json4s


    【解决方案1】:

    这可以通过为a 字段实现自定义序列化函数来实现:

    private def serializeA: PartialFunction[(String, Any), Option[(String, Any)]] = {
      case ("a", x) => x match {
        case None => None
        case _ => Some(("a", x))
      }
    }
    

    并将其添加到隐式Formats

    implicit val formats = DefaultFormats.preservingEmptyValues +
                              FieldSerializer[MyType](serializer = serializeA)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-24
      • 2014-03-08
      • 2021-04-22
      • 2017-05-19
      • 2014-05-20
      • 2015-01-27
      • 2018-06-21
      • 1970-01-01
      相关资源
      最近更新 更多