Elegant Scala YAML parsing using SnakeYAML and MoultingYaml20 Feb 2017
If you ever encounter the necessity of parsing / producing YAML files using Java you already know that SnakeYAML is one of the best way to go.
But if try to use it with Scala well things are not so simple (you can find a good article of Alvin Alexander here), and probably you will find yourself writing this :
That works if you have a simple structure but it does not feel Scala… and if you need to parse a given structure with a compositions of lists, objects and maps the code could be really messy.
MoultingYaml to the resque
Thanks to jcazevedo we have a way to use SnakeYaml in a elegant and more natural way by using MoultingYaml.
MoultingYaml is a Scala wrapper that provides a type-class based serialization and deserialization of custom objects.
How to use it? We can start by adding the following dependency to our
First of all we start by rewriting our Person class in a most natural way :
Then we need to explain to the library how to parse a
Person by writing
Protocol, that contains a list of implicit formats that describes how
the case class should be parsed.
Our protocol will extends the provided
DefaultYamlProtocol that describes
how the standard classes need to be parsed.
In order to build a format we use a provided utility function, that is called
yamlFormatN where N is the number of parameters of our case class.
Now we can parse our yaml (the same as before) like that:
All the code :
What if we want to produce a yaml from a
Person? pretty easy
How about a more complex case? imagine to have a
Team with multiple
developers and a Scrum Master :
In order to parse a team we need to add a
Team class and we need to update
Therefore the code to parse the Team is pretty straightforward:
Check out the MoultingYaml docs for more info on how to get the most out of MoultingYaml. You can find the code used for this post on github.