Extraction using case classes
In the previous sections, we extracted specific fields from the JSON response using Scala extractors. We can do one better and extract full case classes.
When moving beyond the REPL, programming best practice dictates that we move from json4s
types to Scala objects as soon as possible rather than passing json4s
types around the program. Converting from json4s
types to Scala types (or case classes representing domain objects) is good practice because:
It decouples the program from the structure of the data that we receive from the API, something we have little control over.
It improves type safety: a
JObject
is, as far as the compiler is concerned, always aJObject
, whatever fields it contains. By contrast, the compiler will never mistake aUser
for aRepository
.
Json4s
lets us extract case classes directly from JObject
instances, making writing the layer converting JObject
instances to custom types easy.
Let's define a case class representing a GitHub user:
scala...