0Pricing
Scala for Backend Engineering & Functional Programming · 课时

解码为样例类

将 JSON 映射到您的类型。

解码为样例类 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Scala for Backend Engineering & Functional Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「解码为样例类」课时是免费的吗?

是的 — 「解码为样例类」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

「解码为样例类」这节课中我会学到什么?

将 JSON 映射到您的类型。 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「解码为样例类」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?

能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 解析 JSON
  2. 解码为样例类
  3. 编码为 JSON
  4. 自定义编解码器
← 返回 Scala for Backend Engineering & Functional Programming