How-to Guides
How-to guides answer one question each: "How do I do X?" Each guide starts from a goal and shows the code that reaches it. If you are new to ZIO JSON, start with the Getting Started tutorial first.
Encoding and decodingโ
- Control the JSON a type encodes to: rename or drop fields, write wrapper types as bare values, reshape output and tag sealed traits.
- Decode JSON whose shape differs from your case class: rename keys, decode through an intermediate class, or read a
Jsontree when the JSON does not match your fields. - Build an encoder or decoder from an existing one: reuse instances with
map,mapOrFail,contramapandtransform. - Encode a type you do not own: write a codec for a class from a library you cannot change.
- Use your own type as a Map key: write
JsonFieldEncoderandJsonFieldDecoderinstances for dates, wrapper types and enumerations used as map keys. - Write a fast encoder or decoder by hand: implement
unsafeEncodeandunsafeDecodefor hot paths or JSON shapes derivation cannot produce. - Validate data while decoding: reject bad values during decoding.
Shaping the JSONโ
- Field names: rename fields, use snake_case or kebab-case, and add aliases.
- Sealed traits: choose how a sum type is written and read, with type hints or a discriminator field.
- Optional, default and null fields: control missing fields, default values and nulls.
Deriving codecsโ
- Derive codecs on Scala 3: use
derives, agivenconfiguration, enums, union types, generic classes and opaque types. - Derive codecs for generic types: type-parameterised case classes and sealed traits, including recursive ones, on Scala 2 and 3.
Working with the JSON tree and YAMLโ
- Read and edit JSON of unknown shape: navigate, update, delete and merge parts of a
Jsonvalue with cursors. - Load a YAML configuration file: decode YAML into case classes and write case classes back as YAML.
Working with data at scaleโ
- Process large JSON as a stream: read and write large JSON arrays and JSON Lines files without loading them into memory.
- Catch unintended changes to your JSON with golden tests: pin the encoded format in a test and review every change.
Developer toolsโ
- Generate case classes from sample JSON: print case class definitions and codecs inferred from a JSON sample.
For every annotation, see Annotations; for every derivation option, see JsonCodecConfiguration. The Reference section covers the rest of the API.