本文介绍了SnakeYaml堆叠钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的.yml文件时:
When this is my .yml file:
test1: "string1"
test2:
test3: "string2"
如何获取 test3
的值?
Map<String, Object> yamlFile = new Yaml().load(YamlFileInputStream);
yamlFile.get("test1"); // output: string1
yamlFile.get("test2"); // output: {test3=string2}
yamlFile.get("test2.test3"); // output: key not found
推荐答案
YAML没有„ stacked keys".它具有嵌套映射.点.
不是特殊字符,通常可以在键中出现,因此您不能将其用于查询嵌套映射中的值.
YAML does not have „stacked keys". It has nested mappings. The dot .
is not a special character and can occur normally in a key, therefore you cannot use it for querying values in nested mappings.
您已经展示了如何访问包含 test3
键的映射,您可以从那里简单地查询值:
You already show how to access the mapping containing the test3
key, you can simply query the value from there:
((Map<String, Object)yamlFile.get("test2")).get("test3");
但是,将YAML文件的结构定义为类要简单得多:
However, it is much simpler to define the structure of your YAML file as class:
class YamlFile {
static class Inner {
public String test3;
}
public String test1;
public Inner test2;
}
然后您可以像这样加载它:
Then you can load it like this:
YamlFile file = new Yaml(new Constructor(YamlFile.class)).loadAs(
input, YamlFile.class);
file.test2.test3; // this is your string
这篇关于SnakeYaml堆叠钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!