2

I'd like to be able to add a field to certain case classes when they are encoded in JSON vis circe.

e.g.

trait OntologyType {
  val ontologyType: String = this.getClass.getSimpleName
}
case class Thing(i: Int) extends OntologyType

val thing = Thing(23)

println(t.toJson) // 1

case class Thingy(s: Srtring, i: Int) extends OntologyType
val thingy = Thingy("Hi there", 23)

println(t.toJson) // 2

I'd like to find a way for the above to return

{ "i": 23, "type": "Thing" } // 1
{ "s": "Hi there", "i": 23, "type": "Thingy" } // 2

The closest I have got is making all OntologyTypes render their type, but need to somehow mixin the standard case class encoding too:

implicit def encodeUser[T <: OntologyType]: Encoder[T] =
      Encoder.forProduct1("type")(u => (u.ontologyType))
James Gorrie
  • 351
  • 2
  • 6

1 Answers1

1

Try

implicit def encodeUser[T <: OntologyType](implicit enc: DerivedObjectEncoder[T]): Encoder[T] =
  u => enc.encodeObject(u).add("type", u.ontologyType.asJson).asJson

Imports:

import io.circe._
import io.circe.generic.encoding.DerivedObjectEncoder
import io.circe.syntax._
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66