Yaml Parsing from a config file
Solution 1
The YAML parser seems to be returning a Map
. So you should use it like this:
Map config = (Map) yaml.load(input);
Map usersConfig = config.get("Users");
Also what particular YAML parser are you using?
Update 1: If you look at the documentation, the load
method either returns a List
or Map
depending on the contents of your YAML file. As your YAML file starts with a key-value mapping (Users
) and not an array (-
), the load
method returns a Map
which is the appropriate type to be returned in this case.
Solution 2
1) check the validity of your YAML here: http://instantyaml.appspot.com/
2) Your document should look like this: (mind the spaces !)
Users :
- Name : A
Id : x
Addr : 10.0.0.1
- Name : B
Id : y
Addr : 10.0.0.2
ExceptionHandler
Updated on June 04, 2022Comments
-
ExceptionHandler almost 2 years
This is the first time i am using a YAML parser and I am currently stuck at this point
I have a config file which goes something like
Users -Name:A Id : x Addr:10.0.0.1 -Name:B Id :y Addr:10.0.0.2 HomeAddress City:bla bla Country:bla bla Office Address City:abchd Country:bha bha ba
So I thought the best way to parse it would be to have a list like this.
List<Map<String, obj>> Object = (List<Map<String, obj>>) yaml.load(input);
Objective was to access the object by specifying a string. Like Username A, I shld be able to obtain his id and IPAddr (This is the most important to me at the moment). But when I tried this declaration, I got an error like this
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.List at Message.MessagePasser.<init>(MessagePasser.java:34)
Can someone please help me debug this. I am running by a deadline!!:(
-
ExceptionHandler over 12 yearsI am using a SnakeYaml Parser
-
ExceptionHandler over 12 yearsThank you for the clarification. Taking your tip on this one, I modified my code to something like
Map<String,nodeIP> obj = (Map<String,nodeIP>) yaml.load(input);
But inspite of this, I have an error which says it cannot cast java.util.ArrayList to NodeIP type (which is a class defined by me). So Can you suggest some change on this? -
Behrang over 12 years
-
GreenAsJade over 10 yearsYour Update1 is a fantastic tidbit. I just spent an hour trying to work out why code that worked before stopped working ... it's because I ignorantely put a thingo: into my YAML, changing the return value type of the load!!
-
Alex over 8 yearsYour validator does not work anymore, here is another one : yamllint.com . Also, the good formatting seems to remove spaces between keywords and ':' and '-' should be on a empty line, with the attributes coming on CR LF.