我试图用SnakeYAML读取和解析YAML文件,并将其转换为我的Java应用程序的配置POJO:
// Groovy pseudo-code
class MyAppConfig {
List<Widget> widgets
String uuid
boolean isActive
// Ex: MyAppConfig cfg = new MyAppConfig('/opt/myapp/config.yaml')
MyAppConfig(String configFileUri) {
this(loadMap(configFileUri))
}
private static HashMap<String,HashMap<String,String>> loadConfig(String configFileUri) {
Yaml yaml = new Yaml();
HashMap<String,HashMap<String,String>> values
try {
File configFile = Paths.get(ClassLoader.getSystemResource(configUri).toURI()).toFile();
values = (HashMap<String,HashMap<String,String>>)yaml.load(new FileInputStream(configFile));
} catch(FileNotFoundException | URISyntaxException ex) {
throw new MyAppException(ex.getMessage(), ex);
}
values
}
MyAppConfig(HashMap<String,HashMap<String,String>> yamlMap) {
super()
// Here I want to extract keys from 'yamlMap' and use their values
// to populate MyAppConfig's properties (widgets, uuid, isActive, etc.).
}
}例YAML:
widgets:
- widget1
name: blah
age: 3000
isSilly: true
- widget2
name: blah meh
age: 13939
isSilly: false
uuid: 1938484
isActive: false由于SnakeYAML似乎只给我一个HashMap<String,<HashMap<String,String>>来表示我的配置数据,所以我们似乎只能有两个SnakeYAML支持的嵌套映射属性(外部映射和类型为<String,String>的内部映射).
widgets包含一个列表/序列(例如,fizzes),其中包含一个列表(例如,buzzes ),其中包含另一个列表,等等,该怎么办?这仅仅是SnakeYAML的一个限制,还是我使用该API的错误?uuid是否是在映射中定义的属性,不如我可以执行类似yaml.extract('uuid')等的操作,然后再对uuid (和任何其他属性)进行验证。发布于 2016-02-20 13:14:59
你的意思是这样:
@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.*
import org.yaml.snakeyaml.constructor.*
import groovy.transform.*
String exampleYaml = '''widgets:
| - name: blah
| age: 3000
| silly: true
| - name: blah meh
| age: 13939
| silly: false
|uuid: 1938484
|isActive: false'''.stripMargin()
@ToString(includeNames=true)
class Widget {
String name
Integer age
boolean silly
}
@ToString(includeNames=true)
class MyConfig {
List<Widget> widgets
String uuid
boolean isActive
static MyConfig fromYaml(yaml) {
Constructor c = new Constructor(MyConfig)
TypeDescription t = new TypeDescription(MyConfig)
t.putListPropertyType('widgts', Widget)
c.addTypeDescription(t);
new Yaml(c).load(yaml)
}
}
println MyConfig.fromYaml(exampleYaml)显然,这是一个要在Groovy控制台中运行的脚本,您不需要@Grab行,因为您可能已经在类路径中有了库;-)
https://stackoverflow.com/questions/35521788
复制相似问题