Skip to content
Advertisement

How to flatten dynamic yaml file using java

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:

JavaScript

And can fetch it as

JavaScript

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:

JavaScript

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 Objects, 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 Objects to different types.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement