UnMarshalling YAML file to Java Object

This post explains unmarshalling information stored in YAML format to java object . This can be achieved with the help of YAMLMapper provided by jackson package.

To explain with an example we will use the below pojo objects


package package2;

import java.math.BigDecimal;
import java.util.List;

public class Employee {
    private String id;
    private String name;
    private String status;
    private BigDecimal salary;
    private List phoneNumbers;
    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 BigDecimal getSalary() {
        return salary;
    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    public List getPhoneNumbers() {
        return phoneNumbers;
    public void setPhoneNumbers(List phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    public String toString() {
        StringBuilder sb = new StringBuilder();
        return sb.toString();

The Employee YAML data is as shown below


id: "1"
name: "name1"
status: "NEW"
salary: 1000
- "phoneNumber1"
- "phoneNumber2"

Now the main code which does the unmarshalling is as shown below

Main Code

1  package package2;
3  import java.io.File;
4  import java.io.IOException;
6  import com.fasterxml.jackson.core.JsonParseException;
7  import com.fasterxml.jackson.databind.JsonMappingException;
8  import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
10 public class YAMLDemo2 {
11  public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
12      File file = new File("Output2.yml");
14      YAMLMapper yamlMapper = new YAMLMapper();
15      Employee employee = yamlMapper.readValue(file, Employee.class);
17      System.out.println(employee);
18  }
19 }

In the above code at line 14, we create an instance of YAMLMapper.

Then we instruct the YAMLMapper instance to read the file Output2.yml and create an instance of Employee having the data from Output2.yml file.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s