我有一个 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[] value = cfg_map.get("name");
为我提供了对象。如何将其转换为字符串数组?
我尝试使用 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;
关于java - 如何在 Java 中将 YAML 列表转换为字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49156923/