Parsing JSON with Scala
Lately I’ve been looking for a better way to parse JSON in Scala. Working with JSON in any staticly typed language is difficult and a pain to code/maintain. There’s got to be a better way…
In comes Argonaut, a Scala JSON parsing library that enables you to deserialize directly into case classes. Just define your schema, represent it in case classes, and boom you’re done. No casting objects, no traversing nested fields, nothing. It’s a thing of beauty.
Enough talk, let’s get started. Grab argonaut using SBT:
Let’s define a simple schema that might represent a person
To parse this into a case class, all we need is a few lines of Scala
That was too easy, let’s make this more difficult and add a nested JSON structure within our Person schema.
all we have to do is make sure we write our new case class, define the codec, and add it to our existing Person
case class
Two things to note, first the change in numbers following the casecodec
method. The pattern is casecodec<n>
where n is the number of arguments to apply to the case class. Just be sure to increment this number when adding a new parameter to your case class. Second, we made both of our classes implement an abstract class we defined as Serializable
which is necessary when you want to define nested case classes like this.
Let’s add a new parameter to our Person
object called middle_name
. Some people don’t have middle names or choose not to use them
The way to represent an optional parameter is to use an Option
(duh). Just wrap your parameter in an Option
in your case class and Argonaut will take care of the rest for you.
That’s it. Define as many case classes as your heart desires, and nest them as deep as you’d like. Focus your time on processing your content rather than parsing it, enjoy!