Parsing a YAML file

In this post I will explain how to parse a YAML file using Jackson framework.

We need the following jars in our classpath
1) jackson-dataformat-yaml-2.9.6.jar
2) snakeyaml-1.18.jar
3) jackson-annotations-2.9.0.jar
4) jackson-core-2.9.6.jar
5) jackson-databind-2.9.6.jar

First we need to create an instance of YAMLFactory class.

It is factory class used to create instance of YAMLParser (reader) and YAMLGenerator (writer) as shown below

File file = new File("Input.yml");
YAMLFactory yamlFactory = new YAMLFactory();
YAMLParser yamlParser = yamlFactory.createParser(file);

While creating parser instance we need to pass the File instance representing the yaml file from which we need to read.

Each element whether start and end of the object, start and end of array, field name and field values are represented by JsonToken enums.

We retrieve the elements by the help of yamlParser, as shown below

a null value indicates the end of line.

We get the field name and field value in String format using the yamlParser as shown below

Below is the complete code

Main Code

package package1;


import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;

public class YAMLDemo1 {
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        File file = new File("Input.yml");
        YAMLFactory yamlFactory = new YAMLFactory();
        YAMLParser yamlParser = yamlFactory.createParser(file);
        JsonToken jsonToken = yamlParser.nextToken();
        while(jsonToken != null) {
            switch(jsonToken) {
                case START_OBJECT: System.out.println("Object Started");
                case END_OBJECT: System.out.println("Object Ended");
                case START_ARRAY: System.out.println("Array Started");
                case END_ARRAY: System.out.println("Array Ended");
                case FIELD_NAME: System.out.println("Key field: " + yamlParser.getText());
                case VALUE_FALSE:
                case VALUE_NULL:
                case VALUE_NUMBER_FLOAT:
                case VALUE_NUMBER_INT:
                case VALUE_STRING:
                case VALUE_TRUE:
                                default:System.out.println("Key value: " + yamlParser.getText());
            jsonToken = yamlParser.nextToken();

Then Input file is as shown below

Input file

id: "1"
name: "name"
status: "NEW"
salary: 1000
- "phone number1"
- "phone number2"


Object Started
Key field: id
Key value: 1
Key field: name
Key value: name
Key field: status
Key value: NEW
Key field: salary
Key value: 1000
Key field: phoneNumbers
Array Started
Key value: phone number1
Key value: phone number2
Array Ended
Object Ended

Leave a Reply