I've been trying to deserialize the following yaml to a List<Stage>
using SnakeYaml:
- name: Stage1
items:
- item1
- item2
- name: Stage2
items:
- item3
public class Stage {
private String name;
private List<String> items;
public Stage() {
}
public Stage(String name, List<String> items) {
this.name = name;
this.items = items;
}
// getters and setters
}
The closest question I found was SnakeYaml Deserialise Class containing a List of Objects.
After reading it, I am aware of Constructor
and TypeDescriptor
classes, but I am still unable to get it working (I get list of HashMaps, not Stages).
The difference with the question in the link above is that my top-level structure is a list, not a custom object.
Read YAML File as Map in Java The Yaml instance introduces us to methods, such as load() which allow us to read and parse any InputStream , Reader or String with valid YAML data: InputStream inputStream = new FileInputStream(new File("student. yml")); Yaml yaml = new Yaml(); Map<String, Object> data = yaml.
Since the implementation is not thread safe, different threads must have their own Yaml instance.
Write Object to YAML Data is in java POJO object, Create an object mapper with yaml implementation class - YAMLFactory writeValue method creates a yaml file using a POJO object. Finally, POJO data is serialized into YAML format.
yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properties while developing the applications. If you have ever used Elastic Search instance and MongoDB database, both of these applications use YAML(. yml) as their default configuration format.
One way would be to create your own snakeyaml Constructor like this:
public class ListConstructor<T> extends Constructor {
private final Class<T> clazz;
public ListConstructor(final Class<T> clazz) {
this.clazz = clazz;
}
@Override
protected Object constructObject(final Node node) {
if (node instanceof SequenceNode && isRootNode(node)) {
((SequenceNode) node).setListType(clazz);
}
return super.constructObject(node);
}
private boolean isRootNode(final Node node) {
return node.getStartMark().getIndex() == 0;
}
}
and then use it when constructing the Yaml:
final Yaml yaml = new Yaml(new ListConstructor<>(Stage.class));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With