Scala2.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对象扩展“结束,其中有几十个案例类,它们只满足从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文档是如何实现这一策略的,他们似乎都希望我继续创建大量的案例类。有什么想法吗?
发布于 2018-05-23 11:30:29
从JSON提取数据时,Case类不是必需的。您可以根据需要查询已解析的树和转换数据。示例中的值可以提取如下:
import net.liftweb.json._
class MyAppConfig(json : String) {
private implicit val formats = DefaultFormats
private val parsed = parse(json)
def primaryMetricsStore() : String = {
(parsed \ "health" \ "metrics" \ "stores" \ "primary").extract[String]
}
def checkPeriodSeconds() : Int = {
(parsed \ "health" \ "checkPeriodSeconds").extract[Int]
}
}原版医生提供了所有细节。
https://stackoverflow.com/questions/50486832
复制相似问题