Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arcilli/f36aa50fc4e2afcfd22e5c804ae3ac92 to your computer and use it in GitHub Desktop.
Save arcilli/f36aa50fc4e2afcfd22e5c804ae3ac92 to your computer and use it in GitHub Desktop.
ZIO learning - playing with json writing custom encoder/decoder / published by https://github.com/dacr/code-examples-manager #8228864c-7704-45e0-a60b-28cf2f7b5980/506d20fc27d881a3f3cbd1565fc4af1705d6acb9
// summary : ZIO learning - playing with json writing custom encoder/decoder
// keywords : scala, zio, learning, json, pure-functional, @testable
// publish : gist
// authors : David Crosson
// license : Apache
// id : 8228864c-7704-45e0-a60b-28cf2f7b5980
// created-on : 2021-12-30T17:13:06+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $scriptFile
// ---------------------
// using scala 3.1.0
// using lib "dev.zio::zio:2.0.0-RC1"
// using lib "dev.zio::zio-test:2.0.0-RC1"
// using lib "dev.zio::zio-json:0.3.0-RC1-1"
// ---------------------
import zio.*
import zio.json.*
import zio.test.*
import zio.test.Assertion.*
import java.nio.file.Path
case class Something(path: Path)
object Something:
implicit val pathEncoder: JsonEncoder[Path] = JsonEncoder[String].contramap(p => p.toString)
implicit val pathDecoder: JsonDecoder[Path] = JsonDecoder[String].map(p => Path.of(p))
implicit val decoder: JsonDecoder[Something] = DeriveJsonDecoder.gen
implicit val encoder: JsonEncoder[Something] = DeriveJsonEncoder.gen
object JsonTests extends DefaultRunnableSpec:
def spec = suite("derives encoder from existing ones")(
test("path encoder/decoder derivated from string ones") {
val something = Something(Path.of("/tmp"))
assert("""{"path":"/tmp"}""".fromJson[Something])(isRight(equalTo(something))) &&
assertTrue(something.toJson == """{"path":"/tmp"}""")
}
)
JsonTests.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment