Skip to content

Instantly share code, notes, and snippets.

@regadas
Last active March 14, 2018 03:11
Show Gist options
  • Save regadas/83d5ad107aaaba54443fc48a3b4dfdd8 to your computer and use it in GitHub Desktop.
Save regadas/83d5ad107aaaba54443fc48a3b4dfdd8 to your computer and use it in GitHub Desktop.
field based circe decoder
import cats.syntax.functor._
import io.circe.Decoder
import io.circe.generic.auto._
import io.circe.parser.decode
trait Event
case class Foo(x: Int) extends Event
case class Bar(y: String) extends Event
val decoderFoo: Decoder[Foo] = Decoder[Foo].prepare(_.downField("foo-event"))
val decoderBar: Decoder[Bar] = Decoder[Bar].prepare(_.downField("bar-event"))
implicit val decodeFooBar: Decoder[Event] = decoderFoo.or(decoderBar.widen[Event])
decode[Event]("""{"foo-event": {"x": 1}}""")
decode[Event]("""{"bar-event": {"y": "1"}}""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment