Skip to main content
Version: 2.x

Refined Interop

The zio-json-interop-refined module provides ZIO JSON instances for refined types. A refined type A Refined P is a value of type A that is known to satisfy the predicate P, for example String Refined NonEmpty. Encoding writes the underlying A. Decoding reads an A and then checks the predicate, so a payload that breaks it fails to decode.

Installationโ€‹

Add the module to your build.sbt:

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

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

Instancesโ€‹

One import, zio.json.interop.refined._, brings four implicit instances into scope:

InstanceTypeRequires
encodeRefinedJsonEncoder[A Refined P]JsonEncoder[A]
decodeRefinedJsonDecoder[A Refined P]JsonDecoder[A] and refined's Validate[A, P]
encodeFieldRefinedJsonFieldEncoder[A Refined P]JsonFieldEncoder[A]
decodeFieldRefinedJsonFieldDecoder[A Refined P]JsonFieldDecoder[A] and refined's Validate[A, P]

The decoders use refined's refineV, so the error message is the one refined produces for the failed predicate. The field instances let a refined type be the key of a Map; see Map Keys for how keys are encoded.

Encoding and Decoding a Case Classโ€‹

With the import in place, a case class whose fields are refined types derives a full codec like any other case class:

import zio.json._
import zio.json.interop.refined._

import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.numeric.Positive

final case class Person(name: String Refined NonEmpty, age: Int Refined Positive)

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

Encoding writes the plain values. The eu.timepit.refined.auto._ import lets us write the literals "Aurora" and 32 where refined types are expected, checking them at compile time:

Person("Aurora", 32).toJson
// res1: String = "{\"name\":\"Aurora\",\"age\":32}"
note

On Scala 3, refined's auto conversion of literals is not available, so Person("Aurora", 32) does not compile there. Build the refined values with refineV instead, for example refineV[NonEmpty]("Aurora"), which returns an Either. The ZIO JSON instances from this module work the same on both versions.

Decoding valid input succeeds:

"""{ "name": "Aurora", "age": 32 }""".fromJson[Person]
// res2: Either[String, Person] = Right(
// value = Person(name = Aurora, age = 32)
// )

When a value breaks its predicate, decoding fails with refined's message and the path of the field:

"""{ "name": "", "age": 32 }""".fromJson[Person]
// res3: Either[String, Person] = Left(
// value = ".name(Predicate isEmpty() did not fail.)"
// )

"""{ "name": "Aurora", "age": 0 }""".fromJson[Person]
// res4: Either[String, Person] = Left(
// value = ".age(Predicate failed: (0 > 0).)"
// )

Refined Types as Map Keysโ€‹

encodeFieldRefined and decodeFieldRefined make a refined type usable as a Map key, as long as the underlying type has a key codec (String, Int, Long and UUID have built-in ones). Here the keys are stock-keeping unit codes that must match a pattern:

import eu.timepit.refined.string.MatchesRegex

type Sku = String Refined MatchesRegex["[A-Z]{3}-[0-9]{4}"]

val stock: Map[Sku, Int] = Map(("ABC-1234": Sku) -> 5)

The key is written as its plain string:

stock.toJson
// res5: String = "{\"ABC-1234\":5}"

Decoding checks every key, and a key that does not match fails with the key in the error path:

"""{ "ABC-1234": 5 }""".fromJson[Map[Sku, Int]]
// res6: Either[String, Map[Sku, Int]] = Right(value = Map(ABC-1234 -> 5))

"""{ "abc": 5 }""".fromJson[Map[Sku, Int]]
// res7: Either[String, Map[Sku, Int]] = Left(
// value = ".abc(Predicate failed: \"abc\".matches(\"[A-Z]{3}-[0-9]{4}\").)"
// )

See Alsoโ€‹

  • Validate on Decode shows other ways to reject values while decoding, such as JsonDecoder#mapOrFail.
  • Manual Instances explains how to write a decoder for a refined type yourself.

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!