Deserialize JSON Config With Serde

Derive Deserialize to load a configuration from JSON with defaults, rejecting unknown fields so typos in the config surface immediately.

RustConfig Management

Code

rustsnippet
26 lines
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ServerConfig {
    port: u16,
    #[serde(default = "default_workers")]
    workers: usize,
    host: String,
}

fn default_workers() -> usize {
    4
}

fn load(source: &str) -> Result<ServerConfig, serde_json::Error> {
    serde_json::from_str(source)
}

fn main() {
    let json = r#"{"port": 8080, "host": "0.0.0.0"}"#;
    match load(json) {
        Ok(config) => println!("{config:?}"),
        Err(error) => eprintln!("invalid config: {error}"),
    }
}

How it works

Structurally, expect the functions default_workers, load and main and nothing else.

Fallible operations return Result, forcing the caller to handle both arms explicitly. The match expression is exhaustive — the compiler enforces that no case is missing.

Points of care

  • Plan for an install step: serde::Deserialize is a real dependency, resolved by the package manager.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

The primary signature is fn default_workers() -> usize

The entry point wires load together — run it once and the whole demo flows.

Key statements

fn load(source: &str) -> Result<ServerConfig, serde_json::Error> {
    serde_json::from_str(source)
}
fn default_workers() -> usize {
    4
}
match load(json) {
    Ok(config) => println!("{config:?}"),
    Err(error) => eprintln!("invalid config: {error}"),
}

Interactive Tools for This Topic

FAQ

How are errors reported?
Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
Which packages must be installed first?
Yes. The imports resolve to `serde::Deserialize`, which the package manager must provide.