How do I serialize one field “preservingEmptyValues” to null using json4s

蓝咒 提交于 2019-12-11 16:52:44

问题


I am using json4s.

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

This has an output like so:

scala

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

instance

MyType(None, None, 1)

output

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


Without DefaultFormats.preservingEmptyValues the output is like so:

scala

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

instance

MyType(None, None, 1)

output

{ "c": 1 }

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:

scala

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

instance

MyType(None, None, 1)

output

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


How does one achieve this using json4s?

回答1:


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))
  }
}

And adding it to the implicit Formats:

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


来源:https://stackoverflow.com/questions/49758011/how-do-i-serialize-one-field-preservingemptyvalues-to-null-using-json4s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!