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

Employee


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;
    }
    @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);
        return sb.toString();
    }
}

The Employee YAML data is as shown below

Output2.yml


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

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

Main Code


1  package package2;
2  
3  import java.io.File;
4  import java.io.IOException;
5  
6  import com.fasterxml.jackson.core.JsonParseException;
7  import com.fasterxml.jackson.databind.JsonMappingException;
8  import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
9  
10 public class YAMLDemo2 {
11  public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
12      File file = new File("Output2.yml");
13      
14      YAMLMapper yamlMapper = new YAMLMapper();
15      Employee employee = yamlMapper.readValue(file, Employee.class);
16      
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.

Output

1,name1,NEW,1000

Leave a Reply