Forked from dacr/zio-learning-json-3-derives-new-codecs.sc
Created
January 3, 2022 07:34
-
-
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
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
// 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