0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Encoding to JSON

Serialize your data out.

Encoding to JSON is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 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.

Encoders Produce JSON

An Encoder[A] is the dual of a decoder: it turns a Scala value of type A into a Circe Json tree.

From there you serialize to a String for HTTP responses, logs, or storage.

The asJson Syntax

Import io.circe.syntax._ to get the .asJson extension method on any value that has an Encoder in scope.

Primitives and collections work immediately.

import io.circe.syntax._

println(42.asJson.noSpaces)        // 42
println("hi".asJson.noSpaces)      // "hi"
println(List(1,2,3).asJson.noSpaces)  // [1,2,3]

Deriving Encoders

Just like decoders, encoders for case classes are derived. Import io.circe.generic.auto._ for automatic derivation.

Field names become JSON keys and field values are encoded recursively.

import io.circe.generic.auto._
import io.circe.syntax._

case class User(name: String, age: Int)
println(User("Ada", 36).asJson.noSpaces)
// {"name":"Ada","age":36}

Semi-Automatic Encoders

For explicit, reusable instances use deriveEncoder from io.circe.generic.semiauto.

Placing it in the companion object gives you one shared Encoder[User] across the codebase.

import io.circe.Encoder
import io.circe.generic.semiauto._

object User {
  implicit val enc: Encoder[User] = deriveEncoder[User]
}

Building Json by Hand

You can construct JSON directly with Json.obj and key/value pairs, where values use .asJson.

This is handy for ad-hoc shapes that do not map to a case class.

import io.circe.Json
import io.circe.syntax._

val j = Json.obj(
  "ok" -> true.asJson,
  "count" -> 3.asJson
)
println(j.noSpaces)  // {"ok":true,"count":3}

Encoding Options

An Option[A] field encodes Some(x) as the value and None as JSON null by default.

If you would rather omit null keys entirely, you can drop them after encoding, shown later.

case class Account(id: Long, nick: Option[String])
println(Account(7, None).asJson.noSpaces)
// {"id":7,"nick":null}

Dropping Null Values

To omit nulls, transform the resulting Json with .deepDropNullValues.

This recursively removes keys whose value is null, producing cleaner output for optional fields.

val clean = Account(7, None).asJson.deepDropNullValues
println(clean.noSpaces)
// {"id":7}

Pretty Printing Output

Use .spaces2 or .spaces4 for indented, human-readable JSON, and .noSpaces for compact wire format.

For full control over formatting, build a custom Printer.

import io.circe.Printer

val printer = Printer.spaces2.copy(dropNullValues = true)
println(printer.print(Account(7, None).asJson))

Encoding Maps

A Map[String, A] encodes to a JSON object, with map keys becoming JSON keys.

For non-string key types, you must provide a KeyEncoder that renders the key as text.

import io.circe.syntax._

val scores = Map("ada" -> 90, "alan" -> 85)
println(scores.asJson.noSpaces)
// {"ada":90,"alan":85}

Mapping Over Encoders

You can adapt an existing encoder with contramap: supply a function from your type to a type Circe already encodes.

This avoids writing a full encoder from scratch.

import io.circe.Encoder

case class UserId(value: Long)
implicit val enc: Encoder[UserId] =
  Encoder[Long].contramap(_.value)

Encode and Decode Together

When you need both directions, derive a single Codec[A] with deriveCodec, which bundles an encoder and a decoder.

This keeps the two in sync as the case class evolves.

import io.circe.Codec
import io.circe.generic.semiauto._

implicit val codec: Codec[User] = deriveCodec[User]

Quick Check

Test your understanding of encoding to JSON.

Recap

An Encoder[A] turns Scala values into Json. Use .asJson with derived encoders, or build trees with Json.obj.

None becomes null unless you drop it; contramap reuses encoders; deriveCodec bundles both directions.

Frequently asked questions

Is the “Encoding to JSON” lesson free?

Yes — the full text of “Encoding to JSON” 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 “Encoding to JSON”?

Serialize your data out. 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 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Encoding to JSON” 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