Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding Scala None to JSON value using circe

Tags:

json

scala

circe

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 Nones from output whereas setting it to false would encode Nones as null (see also this question). But how can one control this setting on a per field basis?

like image 698
msilb Avatar asked Feb 21 '17 04:02

msilb


Video Answer


1 Answers

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)
like image 71
annedroiid Avatar answered Nov 16 '22 01:11

annedroiid