This post explains marshalling a java object to YAML format and storing it to a file. 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();
}
}
Now the main code which does the marshalling from java object to YAML format.
Main Code
1 package package2;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.math.BigDecimal;
6 import java.util.ArrayList;
7 import java.util.List;
8
9 import com.fasterxml.jackson.core.JsonGenerationException;
10 import com.fasterxml.jackson.databind.JsonMappingException;
11 import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
12
13 public class YAMLDemo1 {
14 public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
15 List phoneNumbers = new ArrayList();
16 phoneNumbers.add("phoneNumber1");
17 phoneNumbers.add("phoneNumber2");
18
19 Employee employee = new Employee();
20 employee.setId("1");
21 employee.setName("name1");
22 employee.setSalary(new BigDecimal(1000));
23 employee.setStatus("NEW");
24 employee.setPhoneNumbers(phoneNumbers);
25
26 File file = new File("Output2.yml");
27
28 YAMLMapper yamlMapper = new YAMLMapper();
29 yamlMapper.writeValue(file, employee);
30 }
31 }
As shown in the main code, we create an instance of YAMLMapper. Refer to line 28
YAMLMapper yamlMapper = new YAMLMapper();
Then we instruct the yamlMapper to convert the java object to YAML formant and save to a file as shown below. Refer to line 29
yamlMapper.writeValue(file, user);
Output
id: “1”
name: “name1”
status: “NEW”
salary: 1000
phoneNumbers:
– “phoneNumber1”
– “phoneNumber2”