Suppose I have the following case classes that need to be serialized as JSON objects using circe:
@JsonCodec
case class A(a1: String, a2: Option[String])
@JsonCodec
case class B(b1: Option[A], b2: Option[A], b3: Int)
Now I need to encode val b = B(None, Some(A("a", Some("aa")), 5)
as JSON but I want to be able to control whether it is output as
{
"b1": null,
"b2": {
"a1": "a",
"a2": "aa"
},
"b3": 5
}
or
{
"b2": {
"a1": "a",
"a2": "aa"
},
"b3": 5
}
Using Printer
's dropNullKeys
config, e.g. b.asJson.noSpaces.copy(dropNullKeys = true)
would result in omitting None
s from output whereas setting it to false
would encode None
s as null
(see also this question). But how can one control this setting on a per field basis?
Circe have added a method dropNullValues
on Json
that uses what Travis Brown mentioned above.
def dropNulls[A](encoder: Encoder[A]): Encoder[A] =
encoder.mapJson(_.dropNullValues)
implicit val entityEncoder: Encoder[Entity] = dropNulls(deriveEncoder)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With