Last active
February 3, 2026 20:18
-
-
Save dacr/20c82d6a5967a4a8e79da6af8662125e 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/9149eb0b8f7989b1392cdf689c828b07740bb265
This file contains hidden or 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
| // 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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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 $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "dev.zio::zio:2.0.13" | |
| //> using dep "dev.zio::zio-test:2.0.13" | |
| //> using dep "dev.zio::zio-json:0.5.0" | |
| // --------------------- | |
| import zio.* | |
| import zio.json.* | |
| import zio.test.* | |
| import zio.test.Assertion.* | |
| import java.nio.file.Path | |
| case class Something( | |
| path: Path | |
| ) derives JsonCodec | |
| object Something: | |
| given JsonEncoder[Path] = JsonEncoder[String].contramap(p => p.toString) | |
| given JsonDecoder[Path] = JsonDecoder[String].map(p => Path.of(p)) | |
| object JsonTests extends ZIOSpecDefault: | |
| 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