How can I use YAML for my Java application?
YAML is human-readable and a cool datat interchange format. It’s lean appearance make it special e.g. for configuration files or when humans view or edit data structures. It’s well suited for hierachical data presentation and you can easily map common data structures.
Jackson and SnakeYaml
Here I present two YAML libaries: Jackson (Dataformat YAML extension) and Snakeyaml. JSON is a basis of YAML, so you can use Jackson for your YAML cases.
Snakeyaml is a only YAML library. I start the Jackson example.
My configuration file looks like this.
[code]
server:
type: simple
id: abc
timeoutMs: 100
database:
user: sam
password: sum
url: ‚jdbc:mysql://localhost:3306/db‘
[/code]
For every part in my configuration I have written separate beans e.g. Server, Database. And my class Configuration includes all these beans.
For Reading a YAML configuration file with Jackson you need to do the following:
[code]
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
InputStream configurationFile = …
Configuration configuration = objectMapper.readValue(configurationFile,Configuration.class);
[/code]
That’s all. Pretty easy, isn’t it?
Now, let’s turn to the Snakeyaml library. With Snakeyaml you also need just a few lines.
[code]
Yaml yaml = new Yaml();
InputStream configurationFile = …;
Configuration configuration = (Configuration) yaml.load(configurationFile);
[/code]
Lesson learned
Both libaries are really easy to use. Snakeyaml has a large feature set, a good documentation and the fingerprint is small (<250 kb). So if you only interested in reading a YAML configuration and you are not have anything to do with JSON, go with Snakeyaml.
On Github you also find examples for writing out YAML files.
Resources
http://yaml.org/
https://github.com/FasterXML/jackson-dataformat-yaml
https://bitbucket.org/asomov/snakeyaml