从配置文件解析 Yaml
这是我第一次使用 YAML 解析器,目前我陷入了困境,
我有一个配置文件,其内容类似于
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
所以我认为解析它的最佳方法是拥有一个这样的列表。
List<Map<String, obj>> Object = (List<Map<String, obj>>) yaml.load(input);
目的是通过指定字符串来访问对象。就像用户名A一样,我应该能够获得他的id和IPAddr(这对我来说是目前最重要的)。但是当我尝试这个声明时,我收到了这样的错误
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.List
at Message.MessagePasser.<init>(MessagePasser.java:34)
有人可以帮我调试这个吗?我正在按时完成任务!!:(
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!!:(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
YAML 解析器似乎返回一个
Map
。所以你应该像这样使用它:另外你正在使用什么特定的 YAML 解析器?
更新 1:如果您查看文档,
load
方法会返回List
或Map
,具体取决于 YAML 文件的内容。由于您的 YAML 文件以键值映射 (Users
) 开头,而不是数组 (-
),因此load
方法会返回一个Map
这是在这种情况下返回的适当类型。The YAML parser seems to be returning a
Map
. So you should use it like this:Also what particular YAML parser are you using?
Update 1: If you look at the documentation, the
load
method either returns aList
orMap
depending on the contents of your YAML file. As your YAML file starts with a key-value mapping (Users
) and not an array (-
), theload
method returns aMap
which is the appropriate type to be returned in this case.1) 在此处检查 YAML 的有效性:http://instantyaml.appspot.com/
2) 您的文档应该看起来像这样:(注意空格!)
1) check the validity of your YAML here: http://instantyaml.appspot.com/
2) Your document should look like this: (mind the spaces !)