java - 如何在 Java 中将 YAML 列表转换为字符串数组?

标签 java yaml snakeyaml

我有一个 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/

相关文章:

java - Java中的volatile关键字-澄清

java - 旋转图像会导致损坏

java - 错误: malformed record literal: - JDBC insert data with self defined type array

java - 如何在转储期间使用 SnakeYaml 控制 yaml 缩进?

java - YAML 文件 : Reading Yaml file and Writing the file in Same Format

java - SnakeYaml 获取堆叠键

java - 有趣的 Shell 输出 : [01;32mtestfile. txt[00m 而不是 testfile.txt

kubernetes - 错误 : selector does not match template labels

azure-devops - 由于提供的客户端 key 无效,Azure cli 无法连接

go - 将 GO YAML 解码为 Map 或 String