I want to parse dynamic yaml files using java into HashMap and access them using dot syntax (i.e “a.b.d”)
Given the following example.yml:
--- a: b: c: "Hello, World" d: 600
And can fetch it as
outPutMap.get("a.b.d"); Results: 600
Any idea How we can achieve this?
Advertisement
Answer
As Thorbjørn said in a comment, a HashMap is probably not the correct data structure for representing a YAML file.
You should try looking into tree structures instead.
Maybe something along the lines of:
public class Node { private final String name; private final Object value; private final Node parent; private final Collection<Node> children = new ArrayList<Node>(); public Node(Node parent, String name) { this.parent = parent; this.name = name; } public Node getParent() { return this.parent; } public String getName() { return this.name; } public Collection<Node> getChildren() { return this.children; } public void addChild(Node child) { child.parent = this; children.add(child); } }
And then you just parse the YAML file line by line and construct nodes as you go, adding all subordinate nodes as children of the closest parent node.
Eventually you’ll have a populated tree structure, starting with the top Node
and going down throughout every Node
in the tree.
You could then write a method that can parse strings in the dot syntax you want and then navigate the tree structure accordingly to find the wanted Node
.
Note that it’s not a good idea to store the values as Object
s, you should implement some sort of value-wrapper like NumberValue (that stores the value as a double
) and StringValue (that stores the value as a String
), so that you don’t have to cast Object
s to different types.