nongtom naja
nongtom naja

Reputation: 11

How can i convert None field from case class to JSON correctly

I have this case class

case class Example(
      exId: String,
      exDes: Option[String] = None)

and I try to convert

Example(exId = 1)

to JSON (example.asJson from io.circe) I actually got

{
"exId" : "1"
"exDes": null
}

But i expected

{
    "exId" : "1"
}

is there anyway to convert like i expected with io.circe ?

Upvotes: 1

Views: 252

Answers (1)

pme
pme

Reputation: 14803

Just use dropNullValues, as it Scala Docs states:

Drop the entries with a null value if this is an object.

Your example looks then:

Example(exId = "1").asJson.dropNullValues

And the result is as you wanted:

{
  "exId" : "1"
}

Upvotes: 2

Related Questions