简体   繁体   中英

How to convert YAML list to a string array in Java?

I have a YAML configuration file have the below list:

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"); gives me the object. How can I convert it to the String array?

I tried with cfg_map.get("name").toString().split("\\n") but it didn't work.

By default, SnakeYAML does not know the underlying types you want your YAML file to be parsed into. 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:

/* 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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