In this tutorial, we will learn how to load YAML data in SnakeYAML.
Loading a YAML formatted String
public class LoadingString {
public static void main(String[] args) {
Yaml yaml = new Yaml();
Object obj = yaml.load(getStringYmlData());
System.out.println("Loaded object type: " + obj.getClass());
System.out.println(obj);
}
public static String getStringYmlData() {
return "name: Joe\n"
+ "phone: 111-111-1111\n"
+ "address: Park Dr, Charlie Hill";
}
} OutputLoaded object type: class java.util.LinkedHashMap {name=Joe, phone=111-111-1111, address=Park Dr, Charlie Hill}
Loading from a file
src/main/resources/person.ymlname: Joe
phone: 111-111-11111
address: Park Dr, Charlie Hill
public class LoadFile {
public static void main(String[] args) throws IOException {
Yaml yaml = new Yaml();
try (InputStream in = LoadFile.class.getResourceAsStream("/person.yml")) {
Object obj = yaml.load(in);
System.out.println("Loaded object type:" + obj.getClass());
System.out.println(obj);
}
}
} OutputLoaded object type:class java.util.LinkedHashMap {name=Joe, phone=111-111-11111, address=Park Dr, Charlie Hill}
Loading multiple YAML documents from a file
Per YAML specification, multiple YAML documents can be added in a single file separated by '---'.
src/main/resources/persons.ymlname: Joe
phone: 111-111-1111
address: Park Dr, Charlie Hill
---
name: Trish
phone: 111-111-11111
address: Small Vine, River Town
public class LoadAll {
public static void main(String[] args) throws IOException {
loadFromFile("/person.yml");
loadFromFile("/persons.yml");
}
private static void loadFromFile(String path) throws IOException {
System.out.printf("-- loading from %s --%n", path);
Yaml yaml = new Yaml();
try (InputStream in = LoadAll.class.getResourceAsStream(path)) {
Iterable<Object> itr = yaml.loadAll(in);
System.out.println("-- iterating loaded Iterable --");
for (Object o : itr) {
System.out.println("element type: " + o.getClass());
System.out.println(o);
}
}
}
} Output-- loading from /person.yml -- -- iterating loaded Iterable -- element type: class java.util.LinkedHashMap {name=Joe, phone=111-111-11111, address=Park Dr, Charlie Hill} -- loading from /persons.yml -- -- iterating loaded Iterable -- element type: class java.util.LinkedHashMap {name=Joe, phone=111-111-1111, address=Park Dr, Charlie Hill} element type: class java.util.LinkedHashMap {name=Trish, phone=111-111-11111, address=Small Vine, River Town}
Example ProjectDependencies and Technologies Used: - snakeyaml 1.18: YAML 1.1 parser and emitter for Java.
- JDK 1.8
- Maven 3.3.9
|