How to convert Java Object to YAML file?

By | November 10, 2023

YAML stands for YAML Ain’t Markup Language is also known as Yet Another Markup Language. It is generally used for configuration files and the data exchange between languages with different data structures. Given below is an example of a YAML file representing information about a website:

YAML
#YAML Example
name: paulsofts
link: https://paulsofts.com
isAvailable: true
tutorials:
  Java
  Spring Boot
  Jenkins
  Kafka
  OOPs
  MySQL
  Mongo
  Design Pattern

Java Object to YAML file

In this tutorial, we are going to use a simple Spring Boot project to convert a Java object to a YAML file.

Steps to convert Java Object to YAML file

Step 1- Create a Spring Boot Project

In this step, we will create a Spring Boot application. Please refer How to Create a Spring Boot Project?

Step 2- Adding dependencies

We can easily convert Java objects to YAML files with the help of libraries such as Jackson or SnakeYAML. In our example, we are going to use SnakeYAML, a popular YAML library for Java. In the spring-boot-starter-web dependency, SnakeYAML came by default. We can also add it explicitly in our pom.xml file.

XML
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.29</version> <!-- Use the latest version available -->
</dependency>

Step 3- Create Model class

For this tutorial, we create an Employee class with three fields: ID, name and email.

Java
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Using Lambok library for getters, setter and constructors
 * @author paulsofts
 */

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
	
	private int id;
	private String name;
	private String email;

}

Step 4- Service layer

In this step, we write our business logic to convert a Java object to Yaml file with the help of SnakeYaml library.

Java
import java.io.FileWriter;
import java.io.IOException;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import com.paulsofts.model.Employee;

/**
 * Representer is used to add the default tag
 * of SnakeYaml .i.e., Map
 * @author paulsofts
 */
@org.springframework.stereotype.Service
public class Service {
	
	public String convertToYaml(Object object) {
		DumperOptions options = new DumperOptions();
		options.setIndent(2);
        options.setPrettyFlow(true);
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        
        /**
         * If we do not use the Representer to add default MAP 
         * tag, the SnakeYaml use fully qualified class name
         * in YAML dump
         */
        Representer representer = new Representer();
        representer.addClassTag(Employee.class, Tag.MAP);
        
        Yaml yaml = new Yaml(representer, options);
		return yaml.dump(object);
	}
	
	public void writeYamlToFile(String yamlString, String file) {
		try(FileWriter writer = new FileWriter(file)){
			writer.write(yamlString);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Step 5- Main Class

Now, we will update the Spring Boot main class and call the service layer methods. In the below code, we autowired the service layer in our Spring Boot main class. As we cannot directly call its method, that’s why we are implementing the CommandLineRunner interface and overriding its run(String… args) method to call the service layer methods.

Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.paulsofts.model.Employee;
import com.paulsofts.service.Service;

@SpringBootApplication
public class ObjectToYamlApplication implements CommandLineRunner {Oion {
		Employee employee = new Employee(1001, "Bhoomika", "bhoomika123@gmail.com");
		String yamlString = this.service.convertToYaml(employee);
		this.service.writeYamlToFile(yamlString, "output.yaml");	
	}
}

Step 6- Testing

As we run our Spring Boot application, we can see in our project root directory that a new file, “output.yaml,” gets created, which will have the Java objects in yaml format.

Java Object to YAML
Fig 1- YAML file

Leave a Reply

Your email address will not be published. Required fields are marked *