amrk7
amrk7

Reputation: 1214

Snakeyaml to convert yaml to pojo

I want to load a list of POJO from my yaml file. Is it possible for me to do that using snake yaml?

my yaml file looks something like this --

- pty1:val1
  pty2:val2

- pty1:val1
  pty2:val2

And my pojo -

class pojo {
  String pty1;
  String pty2;
}

Snakeyaml documentation does say to use loadAs() but that loads a single element. Can I load list of such elements with automatic type binding?

Thanks!

Upvotes: 5

Views: 7989

Answers (2)

amrk7
amrk7

Reputation: 1214

I've started using Jackson's YAML format plugin for serializing and deserializing YAML. Quite friendly.

Upvotes: 3

Nirav Mehta
Nirav Mehta

Reputation: 3

One way to achieve this is to create a class that contains a list of POJO.

class POJOList {
    List<pojo> pojoList;
    public POJOList(List<pojo> pojoList) {
        this.pojoList = pojoList;
    }
}

You can then read the yaml file under the resources folder as:

InputStream in = ClassLoader.getResourceAsStream("pojolist.yaml");
POJOList pojoList = yaml.loadAs(in, POJOList.class);

Upvotes: -2

Related Questions