Approach to load entire YAML file as a tree (Map, or a graph) in Java.

1,527 views
Skip to first unread message

Abhishek K

unread,
Jun 22, 2011, 11:10:50 AM6/22/11
to snakeya...@googlegroups.com
Hi folks,
I have a YAML file of the following type: 

Name : Abhishek kona
Age : 23
Male : True
notification :
    port:1988
    host:run1

I want to load the entire yaml file and have an object on which I am able to lookup like  Obj.get("notification").get("port") and so on.

I have not found any examples of doing that. What would be the most type safe way of doing this.

-Abhishek Kona

Andrey

unread,
Jun 22, 2011, 11:20:32 AM6/22/11
to snakeya...@googlegroups.com
Hi,
Yaml yaml = new Yaml();
Map<String, Object> obj = (Map<String, Object>) yaml.load(input);
System.out.println(obj);

should be enough.

Abhishek Kona

unread,
Jun 22, 2011, 11:40:39 AM6/22/11
to snakeya...@googlegroups.com
For the given YAML file:

Name : Abhishek kona
Age : 23
Male : True
notification :
    port:1988
    host:asdf


This java code throws up an Cannot Cast error:
         Yaml yaml = new Yaml();
        URL sampleYaml = this.getClass().getResource("/Sample.yaml");
        InputStream input = new FileInputStream(new File(
                sampleYaml.getFile()));
        Map<String, Object> objectMap = (Map<String, Object>) yaml.load(input);
        System.out.println("objectMap = " + objectMap);
        Map<String, Object> subObjMap = (Map<String, Object>) objectMap.get("notification");
        System.out.println("subObjMap = " + subObjMap);



Any ideas on what I am doing wrong.
-Abhishek Kona
--
You received this message because you are subscribed to the Google Groups "SnakeYAML" group.
To view this discussion on the web visit https://groups.google.com/d/msg/snakeyaml-core/-/FB2-8QpfORwJ.
To post to this group, send email to snakeya...@googlegroups.com.
To unsubscribe from this group, send email to snakeyaml-cor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/snakeyaml-core?hl=en.

Andrey

unread,
Jun 22, 2011, 11:44:19 AM6/22/11
to snakeya...@googlegroups.com
Use spaces around ':' to distinguish it from a scalar (a String)
You can check here your document structure:

Abhishek Kona

unread,
Jun 23, 2011, 8:09:03 AM6/23/11
to snakeya...@googlegroups.com
Thanks works now.
-Abhishek Kona.
> --
> You received this message because you are subscribed to the Google
> Groups "SnakeYAML" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/snakeyaml-core/-/wadD8FnN2K8J.
Reply all
Reply to author
Forward
0 new messages