1
votes

In my config.yml I have a configuration like this

myObject:
  key1: value1
  key2:value2
  key3: value3

I then have a Dropwizard Configuration class as

public class MyObject {

String key1;
String value1;
String key2;
.. so on

}

How do I read the yml file so that its read as just one hashmap? Is this possible?

2

2 Answers

2
votes

You can read yaml files using jackson's objectmapper, and then give it any type you want. A very basic example for your above yaml would be:

File test_yaml.yaml:

myObject:
  key1: value1
  key2: value2
  key3: value3

Code:

package yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YamlMapParser {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

        InputStream resource = YamlMapParser.class.getResourceAsStream("/yaml/test_yaml.yaml");
        Map readValue = mapper.readValue(resource, Map.class);
        System.out.println(readValue);
    }
}

The important bit is to give Jackson's ObjectMapper a YAMLFactory to work with.

The above code then prints:

{myObject={key1=value1, key2=value2, key3=value3}}

I hope that helps!

Artur

2
votes

When creating a Dropwizard application, the YourApplication class will need to extend Application<YourConfiguration>. So anyway you'll need to create a YourConfiguration class. Now, inside the YourConfiguration class, if you want to avoid listing all properties and corresponding getter/setter, you can define a single property as Map and specify all the key-values under the previously defined property in the yaml file.

config.yml

myMap:
  key1: value1
  key2: value2

YourConfiguration.class

class YourConfiguration extends Configuration {
  Map<String, String> myMap;

  Map<String, String> getConfigMap() {
    return myMap;
  }
}