[英]How to convert YAML list to a string array in Java?
我有一个YAML配置文件,具有以下列表:
name:
- string1
- string2
- string3
我正在读取配置文件,如下所示:
Yaml = _yml = new Yaml();
InputStream in = Resources.getResources("myconfigfile.yml").opendStream();
Map cfg_map = (Map) yaml.load(in);
in.close();
String[] values = cfg_map.get("name");
在此行中, String[] values = cfg_map.get("name");
给我对象。 如何将其转换为String数组?
我尝试使用cfg_map.get("name").toString().split("\\n")
但没有用。
默认情况下,SnakeYAML不知道您希望将YAML文件解析为的基础类型。 您可以通过设置根类型来告诉它文件的结构。 例如(匹配您的输入结构):
class Config {
public List<String> name;
}
然后,您可以像这样加载YAML:
/* We need a constructor to tell SnakeYaml that the type parameter of
* the 'name' List is String
* (SnakeYAML cannot figure it out itself due to type erasure)
*/
Constructor constructor = new Constructor(Config.class);
TypeDescription configDesc = new TypeDescription(Config.class);
configDesc.putListPropertyType("name", String.class);
constructor.addTypeDescription(configDesc);
// Now we use our constructor to tell SnakeYAML how to load the YAML
Yaml yaml = new Yaml(constructor);
Config config = yaml.loadAs(in, Config.class);
// You can now easily access your strings
List<String> values = config.name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.