0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Decoding into Case Classes

Map JSON onto your types.

Decoding into Case Classes is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Decoders Map JSON to Types

A Decoder[A] knows how to read a Json value into a Scala type A.

Circe provides decoders for primitives and collections out of the box, and can build decoders for your own case classes automatically.

A Target Case Class

Suppose your API returns user records. Model the shape with a case class whose field names match the JSON keys.

Matching names is what lets Circe derive a decoder with no manual wiring.

case class User(name: String, age: Int, admin: Boolean)

Automatic Derivation

Import io.circe.generic.auto._ and Circe derives a Decoder[User] implicitly, on demand, wherever one is needed.

You then call decode[User] with no extra boilerplate.

import io.circe.generic.auto._
import io.circe.parser.decode

val json = "{\"name\":\"Ada\",\"age\":36,\"admin\":true}"
val user = decode[User](json)
println(user)  // Right(User(Ada,36,true))

Semi-Automatic Derivation

For better compile times and explicit control, use io.circe.generic.semiauto.deriveDecoder.

You define the decoder once, usually in the companion object, and reuse that single instance everywhere.

import io.circe.Decoder
import io.circe.generic.semiauto._

object User {
  implicit val dec: Decoder[User] = deriveDecoder[User]
}

Decoding Failures

If a required field is missing or has the wrong type, decoding fails with a DecodingFailure.

The failure carries a history of cursor operations, pinpointing exactly which field caused the problem.

val bad = decode[User]("{\"name\":\"Ada\"}")
println(bad)
// Left(DecodingFailure at .age: Missing required field)

Optional Fields in Classes

Make a field Option[A] when the JSON key may be absent or null.

Circe decodes a missing key to None automatically, so you do not need a custom decoder just for optionality.

case class Account(id: Long, nickname: Option[String])

val a = decode[Account]("{\"id\":7}")
println(a)  // Right(Account(7,None))

Default Values

Case class default values can fill in missing JSON keys, but only when you derive with configured derivation that enables defaults.

The circe-generic-extras module provides this via Configuration.default.withDefaults.

import io.circe.generic.extras._

implicit val cfg: Configuration =
  Configuration.default.withDefaults

@ConfiguredJsonCodec
case class Settings(theme: String = "dark")

Nested Case Classes

Decoding composes: if Circe can decode each field's type, it can decode a class that nests other case classes.

Derivation recurses automatically, so a single import handles deeply nested structures.

case class Address(city: String)
case class Person(name: String, address: Address)

val p = decode[Person](
  "{\"name\":\"Ada\",\"address\":{\"city\":\"London\"}}")
println(p)

Renaming Fields

When JSON keys differ from Scala names (for example snake_case), use configured derivation with Configuration.default.withSnakeCaseMemberNames.

This maps created_at to a Scala field createdAt without a hand-written decoder.

import io.circe.generic.extras._

implicit val cfg: Configuration =
  Configuration.default.withSnakeCaseMemberNames

@ConfiguredJsonCodec
case class Event(createdAt: String)

Accumulating Errors

By default decoding fails fast on the first error. decodeAccumulating instead collects all failures into a ValidatedNel.

This is useful for form validation where you want to report every problem at once.

import io.circe.Decoder

val result = Decoder[User]
  .decodeAccumulating(json.hcursor)
// Validated[NonEmptyList[DecodingFailure], User]

Choosing a Derivation Style

Use auto for quick prototypes, semiauto for production code where you want fixed instances and faster compiles.

Reach for generic-extras when you need renaming, defaults, or discriminators.

Quick Check

Test your understanding of decoding into case classes.

Recap

A Decoder[A] turns JSON into typed values. Use generic.auto or semiauto.deriveDecoder for case classes whose names match keys.

Missing keys decode Option fields to None; generic-extras adds defaults and renaming; decodeAccumulating gathers all errors.

Frequently asked questions

Is the “Decoding into Case Classes” lesson free?

Yes — the full text of “Decoding into Case Classes” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Decoding into Case Classes”?

Map JSON onto your types. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Decoding into Case Classes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Parsing JSON
  2. Decoding into Case Classes
  3. Encoding to JSON
  4. Custom Codecs
← Back to Scala for Backend Engineering & Functional Programming