Member-only story

Tiny Scala Guide to Reading and Writing JSON using Circe

Brian Schlining
4 min readJan 17, 2021

--

Photo by Tejasvi Ganjoo on Unsplash

Circe is a Scala library for decoding (reading) and encoding (writing) JSON. I’m a big fan of it’s simplicity, flexibility, and conciseness. This guide walks through a simple use case that illustrates Circe’s basic usage, creating a custom encoder and decoder, and common gotchas.

Below, I’ve created a simple JSON schema. The schema is composed of catalogs, which are named grouping of files, and blobs, which are composed of a URL pointer to a file and its checksum. Every object will have a UUID to uniquely identify it.

JSON Data Model

An example JSON object is below:

Scala Data Model

Circe can model JSON using Scala’s case classes. Our mapping is straight forward with only some minor caveats:

  1. In the JSON, the checksum is represented as Base64 encoded binary; when we decode the JSON we want the checksum decoded to a byte array.
  2. A catalog’s name is optional.
import java.util.UUID

--

--

Brian Schlining
Brian Schlining

Written by Brian Schlining

Polyglot coder. Deep-sea Researcher. Zazen aficionado. I think squids are pretty cool.

No responses yet