Reputation: 1009
I am using SnakeYAML to parse certain configuration/property values to a Configuration object (defined below).
My YAML file looks like this:
# Thread
batchLimit: 1000
threadCountLimit: 2
# Some more config
key: value
# Map
keyMapping: <What goes here?>
My Configuration class looks like this:
public class Configuration{
int batchlimit;
int threadCountLimit;
...
Map<String,String> keyMapping;
}
How do I define the keyMapping
in the YAML file so it can be parsed directly by SnakeYAML?
Upvotes: 55
Views: 144918
Reputation: 883
Yaml file "AppParams.yml" with key-value pairs:
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;
}
}
Reader:
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"
The example above uses these dependencies in 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>
Upvotes: 5
Reputation: 115328
Here is how it can look like:
#MAP
keyMapping:
key1: value1
key2: value2
Generally YAML format has natural support of key-value pairs. Take a look on the following tutorial (just for example): https://github.com/Animosity/CraftIRC/wiki/Complete-idiot's-introduction-to-yaml
Or just google "yaml map" for more details.
Upvotes: 111