我正在使用snakeYaml将某些配置/属性值解析为Configuration对象。
我的yaml文件看起来像这样 -
#Thread
batchLimit: 1000
threadCountLimit: 2
#Some More Config
key: value
#MAP
keyMapping: <What goes here?>
我的配置类看起来像这样 -
public class Configuration{
int batchlimit;
int threadCountLimit;
...
Map<String,String> keyMapping;
}
如何在YAML文件中定义keyMapping
,以便直接通过SnakeYAML读取?
答案 0 :(得分:46)
以下是它的外观:
#MAP
keyMapping:
key1: value1
key2: value2
通常,YAML格式自然支持键值对。 看看下面的教程(仅举例):https://github.com/Animosity/CraftIRC/wiki/Complete-idiot's-introduction-to-yaml
或者只是google“yaml map”了解更多详情。
答案 1 :(得分:1)
具有键值对的Yaml文件“ AppParams.yml”:
someConfig:
key1: value1
key2: value2
POJO:
public class ApplicationParameters {
private Map<String, String> someConfig;
public ApplicationParameters() {
}
public Map<String, String> getSomeConfig() {
return someConfig;
}
public void setSomeConfig(Map<String, String> someConfig) {
this.someConfig = someConfig;
}
}
阅读器:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
File paramFile = new File("AppParams.yml");
ApplicationParameters applicationParameters = mapper.readValue(paramFile, ApplicationParameters.class);
Map<String, String> someConfig = applicationParameters.getSomeConfig();
String key1Value = someConfig.get("key1"); //returns "value1"
上面的示例在POM.xml中使用以下依赖项:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>