简体   繁体   English

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

[英]How to convert YAML list to a string array in Java?

I have a YAML configuration file have the below list: 我有一个YAML配置文件,具有以下列表:

name:
  - string1
  - string2
  - string3

I am reading the configuration file as follows: 我正在读取配置文件,如下所示:

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");

Here in this line String[] values = cfg_map.get("name"); 在此行中, String[] values = cfg_map.get("name"); gives me the object. 给我对象。 How can I convert it to the String array? 如何将其转换为String数组?

I tried with cfg_map.get("name").toString().split("\\n") but it didn't work. 我尝试使用cfg_map.get("name").toString().split("\\n")但没有用。

By default, SnakeYAML does not know the underlying types you want your YAML file to be parsed into. 默认情况下,SnakeYAML不知道您希望将YAML文件解析为的基础类型。 You can tell it the structure of your files by setting the root type. 您可以通过设置根类型来告诉它文件的结构。 For example (matching the structure of your input): 例如(匹配您的输入结构):

class Config {
    public List<String> name;
}

You can then load the YAML like this: 然后,您可以像这样加载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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM