【发布时间】:2018-11-02 08:27:31
【问题描述】:
Scala 2.12 在这里尝试使用 Lift-JSON 来解析配置文件。我有以下myapp.json 配置文件:
{
"health" : {
"checkPeriodSeconds" : 10,
"metrics" : {
"stores" : {
"primary" : "INFLUX_DB",
"fallback" : "IN_MEMORY"
}
}
}
}
还有以下MyAppConfig类:
case class MyAppConfig()
我的myapp.json 将会发展并可能变得非常大,其中包含许多嵌套的 JSON 结构。我不希望必须为每个 JSON 对象创建 Scala 对象,然后将其注入 MyAppConfig,如下所示:
case class Stores(primary : String, fallback : String)
case class Metrics(stores : Stores)
case class Health(checkPeriodSeconds : Int, metrics : Metrics)
case class MyAppConfig(health : Health)
等等。这样做的原因是我最终会得到“config object sprawl”,其中包含几十个案例类,这些案例类的存在只是为了满足从 JSON 到 Scala 的序列化。
相反,我想使用 Lift-JSON 来读取 myapp.json 配置文件,然后让 MyAppConfig 具有从 JSON 中读取/解析值的辅助函数苍蝇:
import net.liftweb.json._
// Assume we instantiate MyAppConfig like so:
//
// val json = Source.fromFile(configFilePath)
// val myAppConfig : MyAppConfig = new MyAppConfig(json.mkString)
//
class MyAppConfig(json : String) {
implicit val formats = DefaultFormats
def primaryMetricsStore() : String = {
// Parse "INFLUX_DB" value from health.metrics.stores.primary
}
def checkPeriodSeconds() : Int = {
// Parse 10 value from health.checkPeriodSeconds
}
}
通过这种方式,我可以挑选出我想向我的应用程序公开(使其可读)的配置。我只是没有遵循 Lift API 文档来了解这种策略是如何实现的,他们似乎都希望我去创建大量的案例类。 有什么想法吗?
【问题讨论】: