CI

Circe

Circe JSON codec library patterns for type-safe JSON encoding and decoding in Scala

Details

Language / Topic
scalaScala
Category
Libraries

Rules

balanced
- Derive codecs with `import io.circe.generic.auto._` for simple case classes — use `io.circe.generic.semiauto.deriveCodec[T]` for explicit derivation.
- Parse JSON with `io.circe.parser.decode[T](jsonString)` — returns `Either[DecodingFailure, T]` — never use `decode` without handling the `Left`.
- Encode with `myObject.asJson` or `Encoder[T].apply(t)` after `import io.circe.syntax._`.
- Handle ADTs with a `discriminator` field: add `@JsonKey` or write manual `Encoder`/`Decoder` instances for polymorphic JSON.
- Use `(c.downField("name").as[String], c.downField("age").as[Int]).mapN(User.apply)` in custom decoders for typed field extraction.
- Use `Decoder.instance { c => c.downField("id").as[Int].map(id => ...) }` for custom decoders — the cursor API navigates nested JSON safely.
- Add `circe-optics` for deep JSON transformations: `root.users.each.name.string.modify(_.toLowerCase)(json)` without full decode/encode.
- Use `Encoder.forProduct3("a", "b", "c")(u => (u.a, u.b, u.c))` for clear field mapping without full auto-derivation.