Read array in YAML with Jackson library
In the blog [Read simple YAML file with JAVA], we have seen how to parse a simple YAML file with the help of Jackson library. Let’s see how to read an array in the YAML file in this topic.
YAML file
empOne: - John Doe - 30
Class to map the yml file
package readyamlfile.readyamlfile;
public class EmpList {
private String[] empOne;
public String[] getEmpOne() {
return empOne;
}
public void setEmpOne(String[] empOne) {
this.empOne = empOne;
}
}
Jackson’s library to read yaml file to EmpList bean
package readyamlfile.readyamlfile;
import java.io.File;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
public class ReadEmpList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
File file = new File("C:\\yml\\emplist.yml");
EmpList emplist = mapper.readValue(file, EmpList.class);
System.out.println(ReflectionToStringBuilder.toString(emplist,ToStringStyle.MULTI_LINE_STYLE));
for (int i=0; i<emplist.getEmpOne().length;i++){
System.out.println(emplist.getEmpOne()[i]);
}
} catch (Exception e) {
}
}
}
The above class has different ways to print the out put of yaml file to the console
Run the above class
readyamlfile.readyamlfile.EmpList@59e84876[
empOne={John Doe,30}
]
John Doe
30
In the next blog, we will see how to read dictionaries with the help of Jackson library