Java – How to convert YAML to JSON using ObjectMapper ?

In this article, we will discuss how to convert YAML file to JSON 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. YAML file to JSON conversion :

In the below illustration, we will convert YAML file to JSON

  • Since we are converting YAML file contents to an Object therefore we need corresponding objects such as Person, Address and Item with default no-argument constructor otherwise an runtime exception will be thrown

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 YAML file to JSON conversion :

  • 1st step is to read the contents of the YAML file to a String
  • 2nd step is to convert YAML file to Person object using readValue() method of ObjectMapper class by passing 2-arguments,
    • Contents read from the YAML file in String format
    • Corresponding class name of the YAML file contents to be converted, in this case Person.class
  • 3rd step is to convert Person object to JSON using ObjectMapper class again
  • Note: a default no-arg constructor is explicitly required for the conversion

YAML file contents – 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"

YamlToJsonConversion.java

package in.bench.resources.yaml.conversion;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YamlToJsonConversion {

	public static void main(String[] args) {

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

		try {
			// 1st step - read contents
			String content = new String(Files.readAllBytes(Paths.get(
					"C:\\Users\\Demo\\eclipse-workspace\\YamlConversion\\Person.yaml")));


			// 2nd step - convert YAML to Person object 
			Person person = mapper.readValue(content, Person.class);


			// 3rd step - YAML -> Person object -> JSON conversion
			ObjectMapper jsonWriter = new ObjectMapper();
			String str = jsonWriter.writerWithDefaultPrettyPrinter().writeValueAsString(person);


			// print to console
			System.out.println(str);

		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output in console :

{
  "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 articles, we will discuss about JSON to YAML file conversion in detail

Related Articles :

References :

Happy Coding !!
Happy Learning !!

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