SnakeYaml 1) is a java library that manages yaml document.
Object to read or write must be:
Log file:
---
Time: 2001-11-23 15:01:42 -5
User: ed
Warning:
This is an error message
for the log file
---
Time: 2001-11-23 15:02:31 -5
User: ed
Warning:
A slightly different error
message.
---
Date: 2001-11-23 15:03:17 -5
User: ed
Fatal:
Unknown variable "bar"
Stack:
- file: TopClass.py
line: 23
code: |
x = MoreObject("345\n")
- file: MoreClass.py
line: 58
code: |-
foo = bar
With SnakeYaml, the data object are LinkedList.
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.20</version>
</dependency>
public void testLoadManyDocuments() throws FileNotFoundException {
InputStream input = new FileInputStream(new File(
"src/test/resources/specification/example2_28.yaml"));
Yaml yaml = new Yaml();
for (Object data : yaml.loadAll(input)) {
System.out.println(data);
}
}
{Time=Fri Nov 23 21:01:42 CET 2001, User=ed, Warning=This is an error message for the log file}
{Time=Fri Nov 23 21:02:31 CET 2001, User=ed, Warning=A slightly different error message.}
{Date=Fri Nov 23 21:03:17 CET 2001, User=ed, Fatal=Unknown variable "bar", Stack=[{file=TopClass.py, line=23, code=x = MoreObject("345\n")
}, {file=MoreClass.py, line=58, code=foo = bar}]}
where:
Built with the dumper option to choose the format and styling.
DumperOptions options = new DumperOptions();
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
StringWriter stringWriter = new StringWriter();
yaml.dump(object, stringWriter);
System.out.println(stringWriter.toString());
The flow style 3) of Yaml is an extended Json format. It means that it adds features such as:
The below code shows you how you can simulate a valid json format.
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
options.setWidth(Integer.MAX_VALUE);
options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED);
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.resolver.Resolver;
public class YamlNoImplicitTagResolver extends Resolver {
/**
* do not resolve float, timestamp, ...
*/
protected void addImplicitResolvers() {
// addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO");
// addImplicitResolver(Tags.FLOAT, FLOAT, "-+0123456789.");
// addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789");
// addImplicitResolver(Tag.INT, INT, "-+0123456789");
// addImplicitResolver(Tag.MERGE, MERGE, "<");
// addImplicitResolver(Tag.NULL, NULL, "~nN\0");
// addImplicitResolver(Tag.NULL, EMPTY, null);
}
}
YamlNoImplicitTagResolver noImplicitTagResolver = new YamlNoImplicitTagResolver();
Yaml yaml = new Yaml(
new Constructor(),
new Representer(),
dumperOptions,
noImplicitTagResolver
);
StringWriter stringWriter = new StringWriter();
yaml.dump(object, stringWriter);
System.out.println(stringWriter.toString());