Saving JSON responses to your model in Scala

If you deal with external APIs (like Twitter, Facebook, Intercom, Github, and many others) on a regular basis there’s a big chance that you have already dealt with JSON answers before.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages.

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

A JSON object can be as simple as

{"key":"value"}

containing just a simple key and value pair - in the limit, it could also be an empty set of key-values pair - or as complex as one wishes it:

Note, actually you just need Json.reads[User] on the companion object. The format allows you to also write a model as JSON directly.

Life ain’t perfect

Unfortunately, some APIs we deal with, are not as nice. Suppose that instead of a isAlive field, the JSON had an is_alive field. Then the mapping between JSON and our model wouldn’t be direct as before.