Member-only story
Tiny Scala Guide to Reading and Writing JSON using Circe
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:
- 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.
- A catalog’s name is optional.
import java.util.UUID