Deserializing YAML data to Java object

In this post under YamlBeans, I will show with an example of how to deserialize a YAML data to Java object.

Main Code


1  import java.io.File;
2  import java.io.FileReader;
3  import java.io.IOException;
4  
5  import com.esotericsoftware.yamlbeans.YamlReader;
6  
7  public class YamlDemo2 {
8   public static void main(String[] args) {
9       File file = new File("input1.yml");
10      YamlReader yamlReader = null;
11      
12      try(FileReader fileReader = new FileReader(file);) {
13          yamlReader = new YamlReader(fileReader);
14          Employee employee = yamlReader.read(Employee.class);
15          yamlReader.close();
16          System.out.println(employee);
17      } catch(IOException excep) {
18          excep.printStackTrace();
19      }
20  }
21 }

At line 13, we will use an instance of YamlReader, which will deserialize the YAML data to Java object.

At line 14, we will call read method of YamlReader class and pass the class information that will be used to deserialize the YAML data.

Employee Class Information


import java.util.List;

public class Employee {
    private String id;
    private String name;
    private String status;
    private float 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 float getSalary() {
        return salary;
    }
    public void setSalary(float 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();
    }
}

Below is the output

Output

1,name1,NEW,1000.0

Leave a Reply