Search code examples
scalacirce

How to remove null values in list of objects using Circe


I'm trying to encode a list of objects using Circe, something that looks similar to:

val test = Seq(MyObject("hello", None, 1, 2, None)

I'm trying to parse this using Circe:

test.asJson

But this creates the JSON object:

[
  {
    name: "hello",
    someVal: null,
    someNum: 1,
    anotherNum: 2,
    anotherVal: null
  }
]

I've tried running asJson with .dropNullValues, but that doesn't seem to access the null values inside of the object. Is there a way to drop the null values inside of the objects?

I'm expecting something more like this:

[
  {
    name: "hello",
    someNum: 1,
    anotherNum: 2
  }
]

Solution

  • Circe provides the function deepDropNullValues in the Json class.

    Example: test.asJson.deepDropNullValues