Skip to main content
Version: 2.x

Getting Started with ZIO Json

Exampleโ€‹

Let's try a simple example of encoding and decoding JSON using ZIO JSON.

All the following code snippets assume that the following imports have been declared

import zio.json.*

Say we want to be able to read some JSON like

{"curvature":0.5}

into a Scala case class

final case class Banana(curvature: Double)

To do this, we derive an instance of the JsonDecoder typeclass for Banana.

final case class Banana(curvature: Double) derives JsonDecoder

Note: If your case class is defining default parameters, -Yretain-trees needs to be added to scalacOptions.

Now we can parse JSON into our object

scala> """{"curvature":0.5}""".fromJson[Banana]
val res: Either[String, Banana] = Right(Banana(0.5))

Likewise, to produce JSON from our data we derive a JsonEncoder

final case class Banana(curvature: Double) derives JsonEncoder
scala> Banana(0.5).toJson
val res: String = {"curvature":0.5}

scala> Banana(0.5).toJsonPretty
val res: String =
{
"curvature" : 0.5
}

And bad JSON will produce an error in jq syntax with an additional piece of contextual information (in parentheses)

scala> """{"curvature": womp}""".fromJson[Banana]
val res: Either[String, Banana] = Left(.curvature(expected a Double))

Say we extend our data model to include more data types

enum Fruit {
case Banana(curvature: Double)
case Apple (poison: Boolean)
}

we can generate the encoder and decoder for the entire sealed family

enum Fruit derives JsonCodec {
case Banana(curvature: Double)
case Apple (poison: Boolean)
}

allowing us to load the fruit based on a single field type tag in the JSON

scala> """{"Banana":{"curvature":0.5}}""".fromJson[Fruit]
val res: Either[String, Fruit] = Right(Banana(0.5))

scala> """{"Apple":{"poison":false}}""".fromJson[Fruit]
val res: Either[String, Fruit] = Right(Apple(false))

Almost all of the standard library data types are supported as fields on the case class, and it is easy to add support if one is missing.

import zio.json.*

enum Fruit derives JsonCodec {
case Banana(curvature: Double)
case Apple(poison: Boolean)
}

export Fruit.*

val json1 = """{ "Banana":{ "curvature":0.5 }}"""
val json2 = """{ "Apple": { "poison": false }}"""
val malformedJson = """{ "Banana":{ "curvature": true }}"""

json1.fromJson[Fruit]
json2.fromJson[Fruit]
malformedJson.fromJson[Fruit]

List(Apple(false), Banana(0.4)).toJsonPretty

How

Extreme performance is achieved by decoding JSON directly from the input source into business objects (inspired by plokhotnyuk). Although not a requirement, the latest advances in Java Loom can be used to support arbitrarily large payloads with near-zero overhead.

Best in class security is achieved with an aggressive early exit strategy that avoids costly stack traces, even when parsing malformed numbers. Malicious (and badly formed) payloads are rejected before finishing reading.

Fast compilation and future-proofing: For Scala 2, derivation uses Magnolia. For Scala 3, derivation uses native Scala 3 macros. zio-json is internally implemented using a java.io.Reader / java.io.Writer-like interface, which is making a comeback to center stage in Loom.

Simplicity is achieved by using well-known software patterns and avoiding bloat. The only requirement to use this library is to know about Scala's encoding of typeclasses, described in Functional Programming for Mortals.

Helpful errors are produced in the form of a jq query, with a note about what went wrong, pointing to the exact part of the payload that failed to parse.

ZIO Chat

Hello! ๐Ÿ˜Š I'm your ZIO Chat Bot, designed to be your go-to resource for all things ZIO! Whether you're new to this powerful functional effect system or a seasoned pro, I'm here to assist you. ZIO empowers you to build concurrent and resilient applications in Scala, offering referential transparency, composable data types, type-safety, and more. So, go ahead and ask me anything about ZIO โ€“ I'm here to provide the answers you need! ๐Ÿค–