Search code examples
rustserde

reading a TOML file with serde - camelCase vs snake_case


I am doing my first forays into rust and I am trying to see how configuration can be read in rust. I am trying the config crate with serde to deserialize the config into a struct:

use config::{Config, File};
use serde::Deserialize;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct DatabaseConfiguration {
  connection_string: String
}

#[derive(Deserialize)]
struct Configuration {
    database: DatabaseConfiguration
}

fn main() {
    println!("Hello, world!");
    let settings = Config::builder()
        .add_source(File::with_name("config"))
        .build()
        .unwrap();
    let config: Configuration = settings.try_deserialize().unwrap();
    println!("Configured settings:");
    println!("connection string: {:?}", config.database.connection_string);
}

with the following toml file:

[database]
connectionString = "https://awesome"

The way I understood the documentation, the rename_all should take care of putting connectionString to connection_string but the try deserialize fails with

missing field `connection_string`

when I change the property in the TOML to snake_case and remove the rename_all part it all works, so it appears that I am misunderstanding how to apply the container attribute from serde.

How is this use case done correctly?


Solution

  • You're hitting an open bug #522 or #5311 in the config crate, downgrading from 0.14.0 to 0.13.4 should work.


    1) I believe both are the same underlying issue