使用Lift-JSON

时间:2018-05-23 11:07:07

标签: json scala lift-json

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-land的序列化。

相反,我想使用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文档来了解这种策略是如何实现的,他们似乎都希望我创建大量的案例类。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

从JSON中提取数据不一定是案例类。您可以根据需要查询已解析的树并转换数据。可以按如下方式提取示例中的值:

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]
  }

}

original doc提供了所有细节。