-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathYamlSerializationExample.java
55 lines (43 loc) · 1.96 KB
/
YamlSerializationExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package org.simpleyaml.examples;
import org.simpleyaml.configuration.file.YamlFile;
import org.simpleyaml.configuration.serialization.ConfigurationSerialization;
/**
* This example shows you how to use this API to serialize and deserialize Objects.
*/
public final class YamlSerializationExample {
public static void main(final String[] args) {
/*
* You can save entire objects in YAML files serializing them.
*
* Before saving or loading objects from file you've to register the class
* to serialize or deserialize.
*
* We will save and load an instance of Person class.
* Take a look to that class to see which methods you have to code to make it work properly.
*/
ConfigurationSerialization.registerClass(Person.class);
final YamlFile yamlFile = new YamlFile("examples/test-serialization.yml");
try {
if (yamlFile.exists()) {
yamlFile.load();
// If the registered class have methods to serialize and deserialize objects,
// this will load the object correctly.
final Person p = (Person) yamlFile.get("test.people.12345678A");
System.out.println("Loaded object:\n " + p);
} else {
yamlFile.createNewFile(true);
System.out.println("New file has been created: " + yamlFile.getFilePath());
// Write an object to the YAML file
final Person p = new Person("12345678A", "John", 1990);
yamlFile.set("test.people." + p.getId(), p);
// Don't forget to save the file!
yamlFile.save();
System.out.println("Restart to load object that has been saved.");
}
// You can delete the generated file uncommenting next line
// yamlFile.deleteFile();
} catch (final Exception e) {
e.printStackTrace();
}
}
}