From the specification: YAML™ (rhymes with “camel”) is a human-friendly, cross language, Unicode based data serialization language.
To get the latest release, simply add the following to your
<dependency> <groupId>com.amihaiemil.web</groupId> <artifactId>camel</artifactId> <version>1.0.2</version> </dependency>
or download the fat jar.
The API of this library is clean, intuitive and generally close to the
javax.json API that most developers are used to:
Building and printing Yaml:
YamlMapping yaml = Yaml.createYamlMappingBuilder() .add("architect", "amihaiemil") .add( "devops", Yaml.createYamlSequenceBuilder() .add("rultor") .add("0pdd") .build() ).add( "developers", Yaml.createYamlSequenceBuilder() .add("amihaiemil") .add("salikjan") .add("SherifWally") .build() ).build();
toString() methods are overriden to pretty-print the yaml, so the above
yaml.toString() will print (notice that the elements are ordered, according to the Yaml specification):
architect: amihaiemil developers: - SherifWally - amihaiemil - salikjan devops: - 0pdd - rultor
Reading a Yaml input is very straight-forward, as outlined bellow. There is one important aspect: the input has to be a valid (well-indented) Yaml, otherwise you will get an exception, at some point, when trying to work with the read object!
//createYamlInput is overloaded to accept also String InputStream YamlMapping yamlMapping = Yaml.createYamlInput(new File("mapping.yml")) .readYamlMapping(); YamlSequence yamlSequence = Yaml.createYamlInput(new File("sequence.yml")) .readYamlSequence();
Parsing a Pojo:
Pojos can be parsed ("dumped") into Yaml as follows (attributes need to have getters and setters):
Map<String, Integer> grades = new HashMap<>(); grades.put("Math", 9); grades.put("CS", 10); YamlMapping studentYaml = new YamlObjectDump( new Student ("John", "Doe", 20, grades) ).represent();
studentYaml.toString() will print:
age: 20 firstName: John grades: CS: 10 Math: 9 lastName: Doe
You can also parse maps (
Map<Object, Object>) and collections (
Contributors are welcome
- Open an issue regarding an improvement you thought of, or a bug you noticed, or ask to be assigned to an existing one.
- If the issue is confirmed, fork the repository, do the changes on a separate branch and make a Pull Request.
- After review and acceptance, the PR is merged and closed.
- You are automatically listed as a contributor on the repo and the project's site (to follow)
Make sure the maven build
$ mvn clean install -Pcheckstyle
passes before making a PR.