【问题标题】:Scala, PureConfig - how to read json config file?Scala,PureConfig - 如何读取 json 配置文件?
【发布时间】:2021-03-14 13:01:47
【问题描述】:

我的资源中有一个简单的config.json 文件:

{
  "configs": [
    {
      "someConfig": {
        "name": "my_name",
        "filters": {
          "name": "new"
        },
        "id": "some-config-id",
        "fixes": {
          "isFixed": true
        }
      }
    }
  ]
}

我还为给定字段创建了case classes

final case class Configs(configs: List[SomeConfig])

  final case class SomeConfig(name: String,
                              filters: Filters,
                              id: String,
                              fixes: Fixes)

  final case class Filters(name: String)

  final case class Fixes(isFixed: Boolean)

现在我想用PureConfig读取这个配置文件:

val configs: Configs = ConfigSource.resources("configs.json").loadOrThrow[Configs]

但我得到了错误:

Exception in thread "main" pureconfig.error.ConfigReaderException: Cannot convert configuration to Configs. Failures are:
- Key not found: 'name'.
- Key not found: 'filters'.
- Key not found: 'id'.
- Key not found: 'fixes'

我还加了ProductHint:

 implicit def hint[A] = ProductHint[A](ConfigFieldMapping(CamelCase, CamelCase))

但这并没有帮助。 如何修复它以从 json 文件中读取配置?

【问题讨论】:

    标签: scala scala-cats circe pureconfig


    【解决方案1】:

    您的案例类与 JSON 不匹配。它应该更像:

    {
      "configs": [
        {
          "name": "my_name",
          "filters": {
            "name": "new"
          },
          "id": "some-config-id",
          "fixes": {
            "isFixed": true
          }
        }     
      ]
    }
    

    请注意缺少 "someConfig": { ... } 作为配置对象的包装器。或者你应该有:

    final case class Configs(configs: List[SomeConfigWrapper])
    
    final case class SomeConfigWrapper(someConfig: SomeConfig)
    
    ...
    

    因为在 JSON 中,"configs" 对象内没有 namefiltersidfixes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 2014-11-17
      • 2021-12-07
      • 1970-01-01
      • 2018-05-16
      • 2019-10-12
      • 1970-01-01
      相关资源
      最近更新 更多