How to Use #[serde(flatten)] for Nested Structures

Use #[serde(flatten)] to merge nested struct fields directly into the parent struct's JSON output.

Use #[serde(flatten)] on a struct field to merge the fields of a nested struct directly into the parent struct's serialized JSON output.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Address {
    city: String,
    zip: String,
}

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    #[serde(flatten)]
    address: Address,
}

fn main() {
    let user = User {
        name: "Alice".to_string(),
        address: Address {
            city: "Seattle".to_string(),
            zip: "98101".to_string(),
        },
    };
    let json = serde_json::to_string_pretty(&user).unwrap();
    println!("{}", json);
}

This outputs:

{
  "name": "Alice",
  "city": "Seattle",
  "zip": "98101"
}