Skip to main content

Encoder

Encoder[A].withFields

With withFields, you can add additional fields to the JSON encoded by an existing Encoder.

import extras.circe.codecs.encoder._

Encoder[A].withFields { a =>
List(
"name1" -> a.someValue1.asJson,
"name2" -> a.someValue2.asJson
)
}

Example

import io.circe._
import io.circe.syntax._
import io.circe.generic.semiauto._
import extras.circe.codecs.encoder._

final case class Something(n: Int) {
def name: String = "Foo"
}

object Something {
implicit val somethingEncoder: Encoder[Something] = deriveEncoder[Something]
.withFields { a =>
List(
"doubled-n" -> (a.n * 2).asJson,
"name" -> a.name.asJson,
"some-fixed-value" -> "blah blah".asJson,
)
}
}

val something = Something(123)
// something: Something = Something(n = 123)
something.asJson
// res1: Json = JObject(
// value = object[n -> 123,doubled-n -> 246,name -> "Foo",some-fixed-value -> "blah blah"]
// )
something.asJson.spaces2
// res2: String = """{
// "n" : 123,
// "doubled-n" : 246,
// "name" : "Foo",
// "some-fixed-value" : "blah blah"
// }"""

Comparison

Let's compare it with the Encoder without withFields syntax.

import io.circe._
import io.circe.syntax._
import io.circe.generic.semiauto._
import extras.circe.codecs.encoder._

final case class Something(n: Int) {
def name: String = "Foo"
}

object Something {
val originalSomethingEncoder: Encoder[Something] = deriveEncoder
implicit val somethingEncoder: Encoder[Something] = originalSomethingEncoder
.withFields { a =>
List(
"doubled-n" -> (a.n * 2).asJson,
"name" -> a.name.asJson,
"some-fixed-value" -> "blah blah".asJson,
)
}
}

val something = Something(123)
// something: Something = Something(n = 123)

Something.originalSomethingEncoder(something)
// res4: Json = JObject(value = object[n -> 123])
Something.originalSomethingEncoder(something).spaces2
// res5: String = """{
// "n" : 123
// }"""

something.asJson
// res6: Json = JObject(
// value = object[n -> 123,doubled-n -> 246,name -> "Foo",some-fixed-value -> "blah blah"]
// )
something.asJson.spaces2
// res7: String = """{
// "n" : 123,
// "doubled-n" : 246,
// "name" : "Foo",
// "some-fixed-value" : "blah blah"
// }"""