如何序列化一个字段"preservingEmptyValues"?使用json4s为null [英] How do I serialize one field "preservingEmptyValues" to null using json4s

查看:233
本文介绍了如何序列化一个字段"preservingEmptyValues"?使用json4s为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用json4s.

I am using json4s.

我知道您可以使用DefaultFormats.preservingEmptyValues以某种类型保留所有Option成员的None值".

I am aware that you can "preserve None values" of all Option members in a type using DefaultFormats.preservingEmptyValues.

其输出如下:

斯卡拉

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

实例

MyType(None, None, 1)

输出

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


没有DefaultFormats.preservingEmptyValues的输出如下:


Without DefaultFormats.preservingEmptyValues the output is like so:

斯卡拉

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

实例

MyType(None, None, 1)

输出

{ "c": 1 }


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


What I would like to do, it keep the default behaviour (removing the property) for one member, say a and use the preservingEmptyValues for another, say b and have an output like so:

斯卡拉

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

实例

MyType(None, None, 1)

输出

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


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


How does one achieve this using json4s?

推荐答案

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

This can be achieved by implementing a custom serialization function for the a field:

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)

这篇关于如何序列化一个字段"preservingEmptyValues"?使用json4s为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆