Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:20
Show Gist options
  • 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/15b1e90280dd90b85cb577b72c383d4f9353f6e7
// 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.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