TestVagrant

How to Read YAML File in Java using YamlBean

How to read Yaml file in Java using YamlBean

Blog

How to Read YAML File in Java using YamlBean

This blog covers how to read YAML files by using the YamlBeans library. Before going to the library let us know the basic details of YAML.

What is YAML?

YAML stands for YAML Ain’t Markup Language.

  • YAML is a very simple, text-based, human-readable language used to exchange data between people and computers.
  • YAML is a data serialization language similar to XML or JSON. However, it is much more human-readable and concise.

What is YamlBean library?

YamlBeans is a free library where it makes easy to serialize and deserialize Java object graphs to and from YAML, a human-friendly data format. Replace XML and properties files with YAML for more expressive power (lists, maps, anchors, etc) and easier hand-editing.

YamlBean as Gradle dependency:

// https://mvnrepository.com/artifact/com.esotericsoftware.yamlbeans/yamlbeans
implementation 'com.esotericsoftware.yamlbeans:yamlbeans:1.15'

Basic deserialization

The YamlReader class is used to deserialize YAML to Java objects.

Scenario: 1

Let’s consider we have placed the Yaml file in resources and need to read the following YAML defines a Map with six entries.

				
					id: '1'
name: name1
phoneNumbers:
  - phoneNumber1
  - phoneNumber2
salary: 1000
status: NEW
age: 35
				
			

Now we need to validate the salary by reading the Yaml. This can be achieved by following steps.

Step 1: Get the file in the project

				
					 public File getFile(String path) {
        return new File(YamlBeansFileReader.class.getClassLoader().getResource(path).getFile());
    }
				
			

Step 2: Use YamlReader to reads the YAML document and deserialize it into HashMaps, ArrayLists, and Strings. Since we know the root object defined in the YAML of our example is a Map, we can cast the object and use it.

				
					public Object readAsObject(File filePath, String value) throws FileNotFoundException, YamlException {
    YamlReader yamlReader = new YamlReader(new FileReader(filePath));
    Map read = (Map) yamlReader.read();
    return read.get(value);
}
				
			

Step 3: Validate the data.

				
					@Test
public void readAsMap() throws YamlException, FileNotFoundException {
    File file = resourceFileReader.getFile("data/employee.yml");
    Object salary = new YamlBeansFileReader().readAsObject(file, "salary");
    System.out.println(salary);       
    Assert.assertTrue(salary.equals("1000"));
}
				
			

OutPut:

Scenario: 2

Deserializing other classes

There are two ways to deserialize something other than HashMaps, ArrayLists, and Strings.

Step 1: Java class for same YAML document:

				
					package com.testvagrant.yamlreader.tests.models;
import java.util.List;

public class Employee {

    private String id;
    private String name;
    private String status;
    private float salary;
    private List phoneNumbers;
    private int age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public float getSalary() {
        return salary;
    }

    public void setSalary(float salary) {
        this.salary = salary;
    }

    public List getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.id).append(",");
        sb.append(this.name).append(",");
        sb.append(this.status).append(",");
        sb.append(this.salary);
        sb.append(this.age);
        return sb.toString();
    }
}
				
			

Step 2: The “read” method can be passed a class, so the YamlReader knows what it is deserializing:

				
					public File getFile(String path) {
        return new File(YamlBeansFileReader.class.getClassLoader().getResource(path).getFile());
    }
				
			
				
					public  T read(File filePath, Class tClass) throws FileNotFoundException, YamlException {
        YamlReader yamlReader = new YamlReader(new FileReader(filePath));
        T obj = yamlReader.read(tClass);
        return obj;
    }

				
			

Step 3: Validate the data

				
					@Test
    public void readAsAnObject() throws YamlException, FileNotFoundException {
        File file = resourceFileReader.getFile("data/employee.yml");
        Employee employee = new YamlBeansFileReader().read(file, Employee.class);
        Assert.assertEquals(employee.getId(), "1");
        Assert.assertEquals(employee.getAge(), 35);
    }
				
			

The YamlReader creates an instance of the Employee class and sets the “id” and “age” fields. The YamlReader determines the “age” value in the YAML needs to be converted into an int. Deserialization would have failed if the age was not a valid int. The YamlReader can set public fields and bean setter methods.

Scenario 3:

YamlReader for nested data in YAML document specified in the YAML using a tag.

				
					name: field3
type: short
length: 2
comment: Error
variableFields:
  - !com.testvagrant.yamlreader.tests.models.VariableField
    id: 1
    name: nestedField 1
    type: Long
    length: 3
    comment:
---
				
			

Step 1: Java class for same YAML document:

				
					package com.testvagrant.yamlreader.tests.models;

import java.util.List;

public class MessageField {
    public String name;
    public String type;
    public int length;
    public String comment;
    public List variableFields;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public List getVariableFields() {
        return variableFields;
    }

    public void setVariableFields(List variableFields) {
        this.variableFields = variableFields;
    }
}
				
			
				
					package com.testvagrant.yamlreader.tests.models;

public class VariableField {
    public int id;
    public String name;
    public String type;
    public int length;
    public String comment;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }
}
				
			

Step 2: The “read” method can be passed a class, so the YamlReader knows what it is deserializing:

				
					 public File getFile(String path) {
        return new File(YamlBeansFileReader.class.getClassLoader().getResource(path).getFile());
    }
				
			
				
					public  T read(File filePath, Class tClass) throws FileNotFoundException, YamlException {
        YamlReader yamlReader = new YamlReader(new FileReader(filePath));
        T obj = yamlReader.read(tClass);
        return obj;
    }
				
			

Step 3: Validate the data

				
					@Test
    public void readByNestedDetails() throws YamlException, FileNotFoundException {
        File file = resourceFileReader.getFile("data/variablefield.yml");
        MessageField field = new YamlBeansFileReader().read(file, MessageField.class);
        Assert.assertTrue(field.getVariableFields().stream()
                .anyMatch(variableField -> variableField.getName().equals("nestedField 1")));
        }
    }
				
			

Any other YAML readers for Java?

Yes, in addition to Yambean, another SnakeYAML Engine, a SnakeYAML reader is available to read YAML documents.

https://yaml.org/

Summary:

Yamlbeans is a Java library commonly used in utilities and applications that handle YAML. YamlBeans makes it easy to serialize and decode Java object graphs to and from YAML, a user-friendly data format. Replace XML files and properties with YAML for more expressive power (lists, maps, anchors, etc) and easier manual editing.

Share This Article

Other Related Articles

Scroll to Top