Ignore "No" field while json encoding with Circe for Scala

I am using Scala 2.11.8 with Circe 0.7.0

I am using scalajs to communicate with an API distinguishing between a non-existent field and a null

field in the sent JSON.

I'm looking for a way to encode in JSON case class

scala containing fields Option[T]

that I would set 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}

      

Any configuration possible from Circe? Do you have any ideas how to access it, I have already looked through all the release notes, github issues and documentation for their website, but no luck.

In case such configuration options are not available, how can someone implement this properly?

+5


source to share


3 answers


Use dropNullKeys :



@param dropNullKeys Determines whether object fields with null values โ€‹โ€‹are removed from the output.

+2


source


Use dropNullValues as mentioned in this link: https://github.com/circe/circe/issues/585



0


source


implicit class JsonWrapper(val json: Json) {
    def removeNulls(): Json = {
      val result = json match {
        case j1 if j1.isArray =>
          j1.mapArray(_.map(_.removeNulls()))

        case j2 if j2.isObject =>
          j2.mapObject(_.removeNulls())

        case v => v
     }
     result
    }
  }

implicit class JsonObjectWrapper(val json: JsonObject) {
    def removeNulls(): JsonObject = {
      json.mapValues{
        case v if v.isObject => v.removeNulls()
        case v if v.isArray  => v.mapArray(_.map(_.removeNulls()))
        case other                => other
      }.filter(!_._2.isNull)
    }
  }

      

0


source







All Articles