Last active
March 20, 2020 10:25
-
-
Save felher/80df90315383b320c2ed79129aa9df72 to your computer and use it in GitHub Desktop.
example circe generic extra configured json codec adt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"street" : "street", | |
"streetNumber" : 3, | |
"zip" : 3, | |
"kind" : "HomeAddress" | |
} | |
{ | |
"street" : "pickupstreet", | |
"streetNumber" : 3, | |
"zip" : 3, | |
"kind" : "PickupStation" | |
} | |
{ | |
"mail" : "[email protected]", | |
"kind" : "Mail" | |
} | |
Right(PickupStation(pickupstreet,3,3)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.felher.tmpNvkhHSWXMk | |
import io.circe.syntax._ | |
import io.circe.parser._ | |
import io.circe._ | |
import io.circe.generic.extras._ | |
import cats.implicits._ | |
object Main { | |
def main(args: Array[String]): Unit = { | |
//Encoder is not contra-variant. | |
implicit def narrow[A <: ContactInformation](implicit enc: Encoder[ContactInformation]): Encoder[A] = enc.narrow[A] | |
println(HomeAddress("street", 3, 3).asJson); | |
println(PickupStation("pickupstreet", 3, 3).asJson); | |
println(Mail("[email protected]").asJson); | |
println(decode[ContactInformation](PickupStation("pickupstreet", 3, 3).asJson.spaces2)) | |
} | |
} | |
@ConfiguredJsonCodec() | |
sealed trait ContactInformation | |
sealed trait Postal extends ContactInformation | |
final case class HomeAddress(street: String, streetNumber: Int, zip: Int) extends Postal | |
final case class PickupStation(street: String, streetNumber: Int, zip: Int) extends Postal | |
final case class Mail(mail: String) extends ContactInformation |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.felher; | |
import io.circe.generic.extras.Configuration | |
package object tmpNvkhHSWXMk { | |
implicit val customConfig: Configuration = Configuration.default.withDiscriminator("kind") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment