【问题标题】:Parsing nested JSON values with Lift-JSON使用 Lift-JSON 解析嵌套的 JSON 值
【发布时间】: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 文档来了解这种策略是如何实现的,他们似乎都希望我去创建大量的案例类。 有什么想法吗?

【问题讨论】:

    标签: json scala lift-json


    【解决方案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 提供所有详细信息。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      • 2019-08-20
      相关资源
      最近更新 更多