Scala, PureConfig - how to read json config file?

1.6k views Asked by At

I have a simple config.json file in my resources:

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

I also created case classes for given fields:

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)

Now I want to read this config file with PureConfig:

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

But I got errors:

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'

I added also ProductHint:

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

But it did not help. How I could fix it to read configs from json file?

1

There are 1 answers

0
Mateusz Kubuszok On BEST ANSWER

Your case classes don't match JSON. It should be something more like:

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

Notice the lack of "someConfig": { ... } as a wrapper for config object. Alternatively you should have:

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

final case class SomeConfigWrapper(someConfig: SomeConfig)

...

because in the JSON you don't have name, filters, id and fixes immediately within "configs" object.