Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore None field while Encoding to json with Circe for Scala

Tags:

json

scala

circe

I am using scala 2.11.8 with circe 0.7.0

I am using scalajs to communicate with an API differentiating non existant field and null field in the sent JSON.

I am looking for a way of encoding to JSON a scala case class containing Option[T] fields that I would set to None to represent missing values:

case class Foo(
optionalFieldOne: Option[Int] = 42,
optionalFieldTwo: Option[Int] = null,
optionalFieldThree: Option[Int] = None
)

implicit FooEncoder: Encoder[Foo] = deriveEncoder[Foo]
val test = Foo()
//What the code actually produces
test.asJson.noSpace
//>{"optionalFieldOne": 42,"optionalFieldTwo":null, "optionalFieldThree":null}

//What I would like
test.asJson.noSpace
//>{"optionalFieldOne": 42,"optionalFieldTwo":null}

Is there any configuration possible provided by circe? Do you have any idea how to access it, I've already looked through all release notes, github issues and their website doc without success.

In the case such configuration options are not available, how would someone implement it properly?

like image 956
amougel Avatar asked Apr 06 '17 08:04

amougel


1 Answers

Use dropNullKeys:

@param dropNullKeys Determines if object fields with values of null are dropped from the output.

like image 148
OlivierBlanvillain Avatar answered Oct 16 '22 01:10

OlivierBlanvillain