Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 6, 2023 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dacr/20c82d6a5967a4a8e79da6af8662125e to your computer and use it in GitHub Desktop.
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/6b609d738bc46c5755b794fc9f28e03d9db38d93
// 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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.2.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