Java – How to convert an Object to YAML using ObjectMapper ?

In this article, we will discuss how to convert an Object to YAML file using ObjectMapper

1. Required libraries :

1.1 Maven Co-ordinates :

<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-yaml</artifactId>
			<version>2.13.4</version>
</dependency>

1.2 JAR files to download :

Download below jar files and include them in Project classpath

1.3 Project class-path :

2. Object to YAML conversion :

In the below illustration, we will convert Person object to YAML file

  • Person object contains a Address object and list of Items

Person.java

package in.bench.resources.yaml.conversion;

import java.util.List;

public class Person {

	// member variables
	private String title;
	private String firstName;
	private String lastName;
	private Address address;
	private List<Item> items;

	// parameterized constructor

	// setters and getters

	// no-arg constrcutor
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	// toString() method
	@Override
	public String toString() {
		return "Person [title=" + title 
				+ ", firstName=" + firstName 
				+ ", lastName=" + lastName 
				+ ",\n address=" + address
				+ ",\n items=" + items 
				+ "]";
	}
}

Address.java

package in.bench.resources.yaml.conversion;

public class Address {

	// member variables
	private String flatNumber;
	private String buildingName;
	private String plotNumber;
	private String sector;
	private String NodeName;
	private String city;
	private String state;
	private String country;

	// parameterized constructor

	// getters and setters

	// no-arg constructor
	public Address() {
		super();
		// TODO Auto-generated constructor stub
	}

	// toString() method
	@Override
	public String toString() {
		return "Address [flatNumber=" + flatNumber 
				+ ", buildingName=" + buildingName 
				+ ", plotNumber=" + plotNumber
				+ ", sector=" + sector 
				+ ", NodeName=" + NodeName 
				+ ", city=" + city 
				+ ", state=" + state 
				+ ", country=" + country 
				+ "]";
	}
}

Item.java

package in.bench.resources.yaml.conversion;

public class Item {

	// member variables
	private String itemName;
	private String itemBoughtYear;

	// parameterized constructor

	// setters and getters

	// no-arg constructor
	public Item() {
		super();
		// TODO Auto-generated constructor stub
	}

	// toString() method
	@Override
	public String toString() {
		return "Item [itemName=" + itemName 
				+ ", itemBoughtYear=" + itemBoughtYear 
				+ "]";
	}
}

2.1 Main class for Object to YAML conversion :

  • Create a Person object using parameterized constructor
  • To convert Person object to YAML, use writeValue() method of ObjectMapper class by passing 2-arguments,
    • location of the file to be written
    • Person object
  • Note: a default no-arg constructor is explicitly required for the conversion

ObjectToYamlConversion.java

package in.bench.resources.yaml.conversion;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.exc.StreamWriteException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class ObjectToYamlConversion {

	public static void main(String[] args) {

		// create Person object
		Person person = getPerson();

		// create ObjectMapper to write to file
		ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

		try {
			System.out.println("1. Writing to a YAML file");
			// write to file
			mapper.writeValue(new File("Person.yaml"), person);
			System.out.println("2. Completed writing to a YAML file");

		} catch (StreamWriteException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * This method returns Person object
	 * 
	 * @return
	 */
	private static Person getPerson() {

		// person
		Person person = new Person(
				"Mr.", 
				"Sam", 
				"Anton", 
				getAddress(), 
				getItems()
				);

		// return
		return person;
	}


	/**
	 * This method returns Address of a Person
	 * 
	 * @return
	 */
	private static Address getAddress() {

		// address
		Address address = new Address(
				"BV-1025", 
				"Shivaji", 
				"1093", 
				"Sector 19", 
				"South Bengaluru", 
				"Bengaluru", 
				"Karnataka", 
				"India"
				);

		// return
		return address;
	}

	/**
	 * This method returns List of Household items
	 * 
	 * @return
	 */
	private static List<Item> getItems() {

		// list of items
		List<Item> items = new ArrayList<Item>();

		// add items
		items.add(new Item("Television", "2014")); // Item 1
		items.add(new Item("Washing Machine", "2020")); // Item 2
		items.add(new Item("Refrigerator", "2011")); // Item 3
		items.add(new Item("Grinder", "2012"));	// Item 4
		items.add(new Item("Computer", "2010"));	// Item 5

		// return
		return items;
	}
}

Output in console :

1. Writing to a YAML file
2. Completed writing to a YAML file

Converted YAML file – Person.yaml

---
title: "Mr."
firstName: "Sam"
lastName: "Anton"
address:
  flatNumber: "BV-1025"
  buildingName: "Shivaji"
  plotNumber: "1093"
  sector: "Sector 19"
  city: "Bengaluru"
  state: "Karnataka"
  country: "India"
  nodeName: "South Bengaluru"
items:
- itemName: "Television"
  itemBoughtYear: "2014"
- itemName: "Washing Machine"
  itemBoughtYear: "2020"
- itemName: "Refrigerator"
  itemBoughtYear: "2011"
- itemName: "Grinder"
  itemBoughtYear: "2012"
- itemName: "Computer"
  itemBoughtYear: "2010"

In the following article, we will discuss about YAML file to Object conversion in detail

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java – How to convert YAML to an Object using ObjectMapper ?
Jackson - Java Object to JSON conversion