Skip to main content
Version: 2.x

Scalaz 7.x Interop

The zio-json-interop-scalaz7x module provides a JsonEncoder and a JsonDecoder for Scalaz 7's immutable list, IList. An IList is written as a JSON array, exactly like a Scala List.

Installationโ€‹

Add the module to your build.sbt:

libraryDependencies += "dev.zio" %% "zio-json-interop-scalaz7x" % "1.1.3"

The module is published for Scala 2.12 and 2.13 only, on the JVM, Scala.js and Scala Native. There is no Scala 3 artifact. In a Scala.js or Scala Native project, use %%% instead of %%.

Instancesโ€‹

The import zio.json.interop.scalaz7x._ brings two implicit instances into scope:

InstanceTypeRequires
ilistEncoderJsonEncoder[IList[A]]JsonEncoder[A]
ilistJsonDecoderJsonDecoder[IList[A]]JsonDecoder[A]

Both convert through List: the encoder writes IList#toList, and the decoder reads a List and builds the IList with IList.fromList.

Encodingโ€‹

Encoding an IList produces a JSON array:

import zio.json._
import zio.json.interop.scalaz7x._

import scalaz._

IList(1, 2, 3).toJson
// res1: String = "[1,2,3]"

Decodingโ€‹

Decoding reads a JSON array into an IList. An element of the wrong type fails with its index in the error path:

"[1, 2, 3]".fromJson[IList[Int]]
// res2: Either[String, IList[Int]] = Right(
// value = ICons(
// head = 1,
// tail = ICons(head = 2, tail = ICons(head = 3, tail = []))
// )
// )

"""[1, "two"]""".fromJson[IList[Int]]
// res3: Either[String, IList[Int]] = Left(value = "[1](expected an Int)")

In a Case Classโ€‹

With the import in scope, case classes with IList fields derive their codecs like any other case class:

final case class Basket(items: IList[String])

object Basket {
implicit val codec: JsonCodec[Basket] = DeriveJsonCodec.gen[Basket]
}

Basket(IList("apple", "pear")).toJson
// res4: String = "{\"items\":[\"apple\",\"pear\"]}"

"""{"items":["plum"]}""".fromJson[Basket]
// res5: Either[String, Basket] = Right(
// value = Basket(items = ICons(head = "plum", tail = []))
// )

ZIO Chat

๐ŸŒŸ Greetings from ZIO Chat! ๐ŸŒŸ Have questions about ZIO? Look no further! I'm here to be your ZIO guru. Whether you're a seasoned pro or just starting out, I've got answers tailored just for you. Fire away with your ZIO queries, and I'll hit you back with the best insights I've got. Let's dive into the world of ZIO together!