[英]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.