Circe: Exclude Options with None

Created on 10 Mar 2017  路  4Comments  路  Source: circe/circe

I'm generating JSON for working with ArangoDB and it distinguishes between null and not set. This creates a problem since the default operation of Circe semi-auto encoding of Option set to None is null. Is there some way to configure this? I would also argue that exclusion should be the default operation anyway since it would result in more compact JSON.

Most helpful comment

dropNullKeys has been changed to the more fitting dropNullValues:

val printer = Printer.noSpaces.copy(dropNullValues = true)

All 4 comments

This looks like a duplicate of #584. Here's an example of how to omit None fields:

scala> :paste
// Entering paste mode (ctrl-D to finish)

import io.circe.generic.auto._
import io.circe.Printer
import io.circe.syntax._

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

val printer = Printer.noSpaces.copy(dropNullKeys = true)


// Exiting paste mode, now interpreting.

import io.circe.generic.auto._
import io.circe.Printer
import io.circe.syntax._
defined class C
printer: io.circe.Printer = Printer(true,true,,,,,,,,,,,,,,,,)

scala> printer.pretty(C(Some("a"), None, false).asJson)
res0: String = {"a":"a","c":false}

scala> printer.pretty(C(None, None, false).asJson)
res1: String = {"c":false}

dropNullKeys has been changed to the more fitting dropNullValues:

val printer = Printer.noSpaces.copy(dropNullValues = true)

Not sure if this is what the OP meant, but it sounds like they are asking for a selective solution - I have something similar with a Tri valued object (think Option, with 2 'None' values, None meaning 'unset'/'set to null', and 'Do not care' meaning ignore that field) - I can just map the 'Some'-ish and the None-ish case to Option, but can't see a way to drop the Json for the Do not care case...

Now that we have dropNullValues on both the printer and Json I think we can close this.

Was this page helpful?
0 / 5 - 0 ratings