Creating Case class event from Configafe Config

Suppose I have a case scala class with serialization capability in json (using json4s or another library):

case class Weather(zip : String, temp : Double, isRaining : Boolean)

If I use the HOCON configuration file :

allWeather {

   BeverlyHills {
    zip : 90210
    temp : 75.0
    isRaining : false
  }

  Cambridge {
    zip : 10013
    temp : 32.0
    isRainging : true
  }

}

Is there a way to use config config to automatically create an object Weather?

I'm looking for something like a form

val config : Config = ConfigFactory.parseFile(new java.io.File("weather.conf"))

val bevHills : Weather = config.getObject("allWeather.BeverlyHills").as[Weather]

The solution could use the fact that the value referenced "allWeather.BeverlyHills"is "blob" json.

I obviously could write my own parser:

def configToWeather(config : Config) = 
  Weather(config.getString("zip"), 
          config.getDouble("temp"), 
          config.getBoolean("isRaining"))

val bevHills = configToWeather(config.getConfig("allWeather.BeverlyHills"))

But this seems inelegant, since any change in the definition of weather will also require a change in configToWeather.

Thank you in advance for your feedback and response.

+6
3

configafe config library API , java bean. , , case .

scala libraries, config config scala , .

, pureconfig

val weather:Try[Weather] = loadConfig[Weather]

Weather - case config

+10

, :

import scala.beans.BeanProperty

//The @BeanProperty and var are both necessary
case class Weather(@BeanProperty var zip : String,
                   @BeanProperty var temp : Double,
                   @BeanProperty var isRaining : Boolean) {

  //needed by configfactory to conform to java bean standard
  def this() = this("", 0.0, false)
}

import com.typesafe.config.ConfigFactory

val config = ConfigFactory.parseFile(new java.io.File("allWeather.conf"))

import com.typesafe.config.ConfigBeanFactory

val bevHills = 
  ConfigBeanFactory.create(config.getConfig("allWeather.BeverlyHills"), classOf[Weather])
+6

- circe.config . . Https://github.com/circe/circe-config

import io.circe.generic.auto._
import io.circe.config.syntax._

def configToWeather(conf: Config): Weather = {
  conf.as[Weather]("allWeather.BeverlyHills") match {
    case Right(c) => c
    case _ => throw new Exception("invalid configuration")
  }
}
0

Source: https://habr.com/ru/post/1649290/


All Articles