Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a list of custom objects with SnakeYaml

Tags:

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.

like image 757
Lesiak Avatar asked May 17 '19 13:05

Lesiak


People also ask

How to read YAML File in Java SnakeYAML?

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.

Is Snakeyaml thread safe?

Since the implementation is not thread safe, different threads must have their own Yaml instance.

How to write YAML File in Java?

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.

What is YAML File in Java?

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.


1 Answers

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));
like image 186
Andreas Berheim Brudin Avatar answered Nov 15 '22 05:11

Andreas Berheim Brudin