问题
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