scalatypesafe

Fail to read configuration with nested keys


With the Ficus library, I am trying to read a configuration file that has the following look:

//myfile.conf
macro: {
  micro: {
    a: "a"
    security.something: "b"
  }
}

When I try to get a Map[String, String] from it, with:

import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.Ficus.toFicusConfig
import net.ceedubs.ficus.readers.ArbitraryTypeReader._

...

myfileConfig.getConfig("macro").as[Map[String, String]](micro)

, I get the following error:

Exception in thread "main" com.typesafe.config.ConfigException$WrongType: myfile.conf @ file:/[XXX]/myfile.conf: 5: security has type OBJECT rather than STRING

I did not find a way around that error. What would be a workaround to this error?

------- EDIT -------

I don't know what the structure could be, nor the keys; but I know it will never be more than one dimension objects, thus limited to generics.

So the idea behind is to get the configuration no matter what the structure interpreted as (String, String).


Solution

  • I have found something of my conveniance:

    import scala.collection.JavaConversions._
    
    implicit class ConfigurationBouiboui(myConfiguration: Config) {
    
      def load[T](name: String): Map[String, T] = {
    
        myConfiguration // configuration before target
          .getConfig(name).entrySet() // configuration as path-value pairs
          .map(x => (x.getKey, x.getValue.unwrapped().asInstanceOf[T])) // (dirty) cast value to T
          .toMap
      }
    }
    

    With:

    // complex.conf
    complex: {
      a: "a"
      b: {
        ba: "4"
        bb: 4
        bc: {
          bca: "bca"
        }
      }
      c: "c"
    }
    

    , I get:

    val config = ConfigFactory.load("complex.conf")
    
    val configurationMap = load(complex)
    
    println(configurationMap)
    
    //outputs: Map(b.bc.bca -> bca, a -> a, b.bb -> 4, b.ba -> 4, c -> c)