How to convert the yaml file into a array using java

5.9k Views Asked by At

i need to access the yaml file data into the java file. i used the YamlReader class and now the yaml file is loaded into the java class object. now all the information is in object and i want to extract it from this object.How can i do this . Can any one help me please i am stuck with this problem.

3

There are 3 best solutions below

0
On

You can read into a Map:

YamlReader reader = new YamlReader(new FileReader("contact.yml"));
Object object = reader.read();
System.out.println(object);
Map map = (Map)object;
System.out.println(map.get("address"));

Source: http://code.google.com/p/yamlbeans/

0
On
Yaml yaml = new Yaml();
String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae";
List<String> list = (List<String>) yaml.load(document);
System.out.println(list);
0
On

Using snakeyaml, the code below didn't work for me. When the yaml object returned my object, it returned a LinkedHashMap type. So I cast my returned object into a LinkedHashMap.

public class YamlConfig {

    Yaml yaml = new Yaml();
    String path = "blah blah";
    InputStream input = new FileInputStream(new File(this.path));
    LinkedHashMap<String,String> map;

    @SuppressWarnings("unchecked")
    private void loadHashMap() throws IOException {
        Object data = yaml.load(input);// load the yaml document into a java object
         this.map = (LinkedHashMap<String,String>)data;
         System.out.println(map.entrySet()); //use this to look at your hashmap keys
         System.out.println(map);//see the entire map
    }