Search code examples
javascalaconfigurationconfigconfiguration-files

Creating a map in config files


We have one application where we use configuration files and they have fields as arrays and normal variables:

metadata {
   array=["val1", "val2"]
   singleValue=2.0
}

Now, I know how to extract these above values like

config.getStringList("metadata.array").asScala.toArray

and config.getString("metadata.singleValue)

But, is there any way I can define maps here so that I can find value wrt desired key from that map. This config is an object of public interface Config extends com.typesafe.config.ConfigMergeable


Solution

  • You can use config.getConfig("metadata") to obtain a (sub)config object.

    Converting the (sub)config to a map is something you'll have to do yourself. I would use config.entrySet() to obtain the entries as key-values, and load it into a map that way.

    I haven't tried compiling/testing this code, but something like this should work:

    Map<String,Object> metadata = new HashMap<>();
    for (Map.Entry<String,ConfigValue> entry : config.entrySet()) {
        metadata.put(entry.getKey(), entry.getValue().unwrapped());
    }