Skip to content

Instantly share code, notes, and snippets.

@pshirshov
Created March 3, 2018 00:39
Show Gist options
  • Save pshirshov/a52f570a97d4f6ebec9fbe9d0fc76a67 to your computer and use it in GitHub Desktop.
Save pshirshov/a52f570a97d4f6ebec9fbe9d0fc76a67 to your computer and use it in GitHub Desktop.
circe with polymorphism
import OT.{OT1, OT2}
import _root_.io.circe._
import _root_.io.circe.generic.semiauto._
import _root_.io.circe.syntax._
import io.circe.parser._
//import _root_.io.circe.java8.time._
decode[List[Int]](List(123, 456).asJson.noSpaces)
sealed trait ST
object ST {
case class ST1(a: Int) extends ST
object ST1 {
implicit val decode: Decoder[ST1] = deriveDecoder
implicit val encode: Encoder[ST1] = deriveEncoder
}
case class ST2(a: Boolean) extends ST
object ST2 {
implicit val decode: Decoder[ST2] = deriveDecoder
implicit val encode: Encoder[ST2] = deriveEncoder
}
implicit val decodeT: Decoder[ST] = deriveDecoder
implicit val encodeT: Encoder[ST] = deriveEncoder
}
decode[ST]((ST.ST1(1) : ST).asJson.noSpaces)
decode[List[ST]](List[ST](ST.ST1(1), ST.ST2(true)).asJson.noSpaces)
trait OT
object OT {
case class OT1(a: Int) extends OT
object OT1 {
implicit val decode: Decoder[OT1] = deriveDecoder
implicit val encode: Encoder[OT1] = deriveEncoder
}
case class OT2(a: Boolean) extends OT
object OT2 {
implicit val decode: Decoder[OT2] = deriveDecoder
implicit val encode: Encoder[OT2] = deriveEncoder
}
implicit val encodeEvent: Encoder[OT] = Encoder.instance {
c => {
c match {
case v: OT1 =>
Map("OT1" -> v).asJson
case v: OT2 =>
Map("OT2" -> v).asJson
}
}
}
implicit val decodeEvent: Decoder[OT] = Decoder.instance(c => {
val fname = c.keys.flatMap(_.headOption).toSeq.head
fname match {
case "OT1" => c.downField(fname).as[OT1]
case "OT2" => c.downField(fname).as[OT2]
}
}
)
}
List[OT](OT.OT1(1), OT.OT2(true)).asJson.noSpaces
decode[OT]((OT.OT1(1) : OT).asJson.noSpaces)
decode[List[OT]](List[OT](OT.OT1(1), OT.OT2(true)).asJson.noSpaces)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment