Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 13 · Testing, macros & unsafe

    13.2Macros & serde

    What Rust macros are and when to write one, how derive writes trait implementations for your types, and how serde turns structs into JSON and back without runtime reflection.

    About 30 minutesIntermediate

    On this page
    1. Concept map
    2. The ! means macro
    3. Writing a macro with macro_rules!
    4. derive writes trait implementations for you
    5. JSON with serde
    6. Bad input is an error, not a surprise
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Code that writes codeNone built in; decorators are functions that run at runtimeSource generatorsMacros: macro_rules! and procedural macros, run by the compiler
    Formatting text with placeholdersTemplate literalsString interpolationformat! and println!, checked at compile time
    Generated equality and printingNone: === compares referencesA record gets Equals and ToString from the compiler#[derive(PartialEq, Debug)]
    Object to JSONJSON.stringifyJsonSerializer.Serialize, through reflection or a source generatorserde_json::to_string, with #[derive(Serialize)]
    JSON to a typed objectJSON.parse returns any: validate it by hand or with a schema libraryJsonSerializer.Deserialize<T>: missing properties get default valuesserde_json::from_str, with #[derive(Deserialize)]: a missing or mistyped field is an error
    camelCase keys for snake_case fieldsName the properties in camelCaseJsonSerializerDefaults.Web, or [JsonPropertyName]#[serde(rename_all = "camelCase")]

    TypeScript’s types disappear when the code runs, so JSON.parse hands you any, and checking that the data has the right shape is up to you.C# can inspect your types while the program runs, so System.Text.Json reads a class’s properties through reflection, or, with a source generator, has the serialization code written at build time. Rust has no runtime reflection: a running program can’t list a struct’s fields. Instead, it has macros: code that writes code while your program compiles. You’ve used them since your first println!. This lesson shows what they do, how to write a small one, and how #[derive] and the serde crate turn your structs into JSON and back.

    The ! means macro

    A name followed by ! is a macro call, not a function call. You’ve already used several:

    TypeScript
    summary.ts
    const items = ["tea"];
    items.push("scones");
    const name = "Ada";
    const summary = `${name} ordered ${items.length} items: ${items.join(", ")}`;
    console.log(summary);
    C#
    Summary.cs
    List<string> items = ["tea"];
    items.Add("scones");
    var name = "Ada";
    var summary = $"{name} ordered {items.Count} items: {string.Join(", ", items)}";
    Console.WriteLine(summary);
    Rust
    let mut items = vec!["tea"];
    items.push("scones");
    let name = "Ada";
    let summary = format!("{name} ordered {} items: {}", items.len(), items.join(", "));
    println!("{summary}");

    Output

    Ada ordered 2 items: tea, scones

    Here’s what each one turns into, in spirit:

    • vec!["tea"] builds a Vec holding the elements you list, as if you’d created an empty Vec and pushed each one. It accepts any number of elements, which a function can’t.
    • format!(...) reads its format string at compile time. The compiler matches each {} to an argument, checks that the argument can be displayed, and generates code that writes the pieces into a new String. Nothing parses the format string while the program runs.
    • println!(...) does the same and writes the result to standard output, with a newline.

    Why aren’t these functions? A Rust function has a fixed list of parameters with fixed types: no overloads, no optional parameters and no variable argument lists such as params. A macro receives the code you wrote between its brackets and can expand to whatever code fits it. That’s also how a mistake in a format string becomes a compile error instead of odd output:

    let items = vec!["tea", "scones"];
    println!("Items: {}", items);

    Rust doesn't compile this: error E0277

    error[E0277]: `Vec<&str>` doesn't implement `std::fmt::Display`
     --> main.rs:2:23
      |
    2 | println!("Items: {}", items);
      |                  --   ^^^^^ `Vec<&str>` cannot be formatted with the default formatter
      |                  |
      |                  required by this formatting parameter
      |
      = help: the trait `std::fmt::Display` is not implemented for `Vec<&str>`
      = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
      = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

    {} asks for the Display trait, user-facing formatting, and a Vec doesn’t have it. Use {:?} (the Debug trait) to print it. A template literal never fails like this: ${items} prints tea,scones, and an object prints [object Object].String interpolation never fails like this: {items} compiles and prints the type name, System.Collections.Generic.List`1[System.String].

    Macros can be called with (), [] or {}; by convention vec! uses square brackets. Others you’ll meet often: assert_eq! (from Tests & doc tests), panic!, todo!, matches!, write! and dbg!.

    Writing a macro with macro_rules!

    dbg!(price * quantity) prints the expression’s source text and its value, which a function can’t do: a function receives only the value. Here’s a smaller version of that idea, which prints any number of expressions:

    TypeScript
    show.ts
    function show(expression: string, value: number): void {
      console.log(`${expression} = ${value}`);
    }
    
    const price = 20;
    const quantity = 3;
    // The expression's text has to be typed twice.
    show("price * quantity", price * quantity);
    show("price + 5", price + 5);
    C#
    Show.cs
    using System.Runtime.CompilerServices;
    
    var price = 20;
    var quantity = 3;
    Show(price * quantity);
    Show(price + 5);
    
    static void Show(int value, [CallerArgumentExpression(nameof(value))] string expression = "")
    {
        Console.WriteLine($"{expression} = {value}");
    }
    Rust
    macro_rules! show {
        ($($value:expr),+) => {
            $(
                println!("{} = {:?}", stringify!($value), $value);
            )+
        };
    }
    
    fn main() {
        let price = 20;
        let quantity = 3;
        show!(price * quantity, price + 5);
    }

    Output

    price * quantity = 60
    price + 5 = 25

    TypeScript has no way to see the text of an argument, so the caller types it twice and it can drift out of date.C# 10 added [CallerArgumentExpression] for exactly this, one argument at a time. A macro can do it for any number of arguments. Read macro_rules! like a match on code:

    • (pattern) => { expansion }; is one rule. A macro can have several, tried in order, like the arms of a match.
    • $value:expr matches one Rust expression and names it $value. The part after the colon is a fragment type: what kind of code to match.
    • $( ... ),+ matches the part inside one or more times, separated by commas. In the expansion, $( ... )+ repeats its contents once for each match, so show!(a, b) becomes two println! calls.
    • stringify!($value) turns the matched code into a string literal at compile time. That’s how the macro gets "price * quantity".

    The fragment types you’ll use most:

    FragmentMatchesExample
    exprAn expressionprice * quantity, items.len()
    identA nameprice, Order
    tyA typeu32, Vec<String>
    literalA literal value42, "tea"
    ttOne token, or a group in bracketsAnything: the most flexible, and the hardest to read

    Macros are hygienic: a variable the expansion declares can’t clash with one at the call site. And a macro_rules! macro must be defined above the code that uses it in the file. To use one from another crate, mark it #[macro_export].

    derive writes trait implementations for you

    The other kind of macro is a procedural macro: a Rust function that the compiler runs on your code, which returns new code. The kind you’ll use every day is derive, written as an attribute on a struct or enum:

    #[derive(Debug, Clone, PartialEq)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    fn main() {
        let a = Point { x: 1, y: 2 };
        let b = a.clone();
        println!("{a:?}");
        println!("{a:#?}");
        println!("{}", a == b);
    }

    Output

    Point { x: 1, y: 2 }
    Point {
        x: 1,
        y: 2,
    }
    true

    Each name in #[derive(...)] generates one trait implementation from the struct’s fields: Debug makes {:?} (and the multi-line {:#?}) work, Clone adds .clone(), PartialEq makes == compare field by field. Without them, Point can do none of those things. Standard traits covers the full set.

    TypeScript generates none of this. console.log inspects an object while the program runs, === compares references, and copying takes structuredClone or a spread:

    point.ts
    type Point = { x: number; y: number };
    
    const a: Point = { x: 1, y: 2 };
    const b: Point = structuredClone(a);
    console.log(a);
    console.log(a === b);

    Output

    { x: 1, y: 2 }
    false

    The closest thing in C# is a record: the compiler writes ToString, Equals, GetHashCode and a copy method for you.

    Point.cs
    var a = new Point(1, 2);
    var b = a with { };
    Console.WriteLine(a);
    Console.WriteLine(a == b);
    
    record Point(int X, int Y);

    Output

    Point { X = 1, Y = 2 }
    True

    derive is the same idea, but you pick each piece, and it works on any struct or enum.

    The generated code is ordinary Rust. #[derive(Debug)] on Point writes roughly this:

    use std::fmt;
    
    struct Point {
        x: i32,
        y: i32,
    }
    
    impl fmt::Debug for Point {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("Point")
                .field("x", &self.x)
                .field("y", &self.y)
                .finish()
        }
    }
    
    fn main() {
        println!("{:?}", Point { x: 1, y: 2 });
    }

    Output

    Point { x: 1, y: 2 }

    Any crate can provide its own derives. The most widely used is serde’s.

    JSON with serde

    serde is the standard Rust library for serialization. It comes in two parts: the serde crate provides the Serialize and Deserialize traits and their derives, and a format crate such as serde_json reads and writes one format. Add both to Cargo.toml, with serde’s derive feature turned on:

    [dependencies]
    serde = { version = "1", features = ["derive"] }
    serde_json = "1"
    

    Here’s an order that goes to JSON and back. The JSON uses camelCase keys, and the coupon code is optional:

    TypeScript
    order.ts
    type Order = {
      orderId: number;
      customerName: string;
      items: string[];
      couponCode?: string;
    };
    
    // JSON.parse returns `any`, so every field is checked by hand.
    function parseOrder(json: string): Order {
      const data = JSON.parse(json) as Record<string, unknown>;
      const { orderId, customerName, items, couponCode } = data;
      if (typeof orderId !== "number" || typeof customerName !== "string") {
        throw new Error("orderId must be a number and customerName a string");
      }
      if (!Array.isArray(items) || !items.every((item): item is string => typeof item === "string")) {
        throw new Error("items must be a list of strings");
      }
      if (couponCode != null && typeof couponCode !== "string") {
        throw new Error("couponCode must be a string");
      }
      return { orderId, customerName, items, ...(couponCode != null ? { couponCode } : {}) };
    }
    
    const order: Order = { orderId: 42, customerName: "Ada", items: ["tea", "scones"] };
    console.log(JSON.stringify(order));
    
    const inputs = [
      '{"orderId":7,"customerName":"Grace","items":["tea"],"couponCode":"WELCOME"}',
      '{"orderId":8,"customerName":"Linus","items":[]}',
    ];
    for (const json of inputs) {
      const parsed = parseOrder(json);
      console.log(`${parsed.customerName}: ${parsed.couponCode ?? "no coupon"}`);
    }
    C#
    Order.cs
    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    var order = new Order(42, "Ada", ["tea", "scones"], null);
    Console.WriteLine(JsonSerializer.Serialize(order, OrderJson.Default.Order));
    
    string[] inputs =
    [
        """{"orderId":7,"customerName":"Grace","items":["tea"],"couponCode":"WELCOME"}""",
        """{"orderId":8,"customerName":"Linus","items":[]}""",
    ];
    foreach (var json in inputs)
    {
        var parsed = JsonSerializer.Deserialize(json, OrderJson.Default.Order)!;
        Console.WriteLine($"{parsed.CustomerName}: {parsed.CouponCode ?? "no coupon"}");
    }
    
    record Order(int OrderId, string CustomerName, List<string> Items, string? CouponCode);
    
    // The source generator writes the serialization code for Order at build time.
    [JsonSourceGenerationOptions(JsonSerializerDefaults.Web, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
    [JsonSerializable(typeof(Order))]
    partial class OrderJson : JsonSerializerContext;
    Rust
    use serde::{Deserialize, Serialize};
    
    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct Order {
        order_id: u32,
        customer_name: String,
        items: Vec<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        coupon_code: Option<String>,
    }
    
    fn main() -> Result<(), serde_json::Error> {
        let order = Order {
            order_id: 42,
            customer_name: String::from("Ada"),
            items: vec![String::from("tea"), String::from("scones")],
            coupon_code: None,
        };
        println!("{}", serde_json::to_string(&order)?);
    
        let inputs = [
            r#"{"orderId":7,"customerName":"Grace","items":["tea"],"couponCode":"WELCOME"}"#,
            r#"{"orderId":8,"customerName":"Linus","items":[]}"#,
        ];
        for json in inputs {
            let parsed: Order = serde_json::from_str(json)?;
            let coupon = parsed.coupon_code.as_deref().unwrap_or("no coupon");
            println!("{}: {coupon}", parsed.customer_name);
        }
        Ok(())
    }

    Output

    {"orderId":42,"customerName":"Ada","items":["tea","scones"]}
    Grace: WELCOME
    Linus: no coupon
    • #[derive(Serialize, Deserialize)] generates the code that writes an Order and reads one, field by field.
    • #[serde(rename_all = "camelCase")] maps order_id to "orderId", in both directions. The struct keeps Rust’s snake_case names. A single field can be renamed with #[serde(rename = "id")].
    • Option<String> makes a field optional: a missing key or null reads as None. By default, None is written as null; skip_serializing_if = "Option::is_none" leaves the key out instead, as JSON.stringify does for undefinedlike WhenWritingNull.
    • serde_json::to_string and serde_json::from_str do the work; to_string_pretty writes indented JSON. The type annotation let parsed: Order tells from_str what to build.

    The C# version uses the System.Text.Json source generator (OrderJson) because this site runs its C# examples as .NET 10 file-based apps, which turn reflection-based serialization off. In an ordinary project, JsonSerializer.Serialize(order, options) and JsonSerializer.Deserialize<Order>(json, options) work through reflection, with no extra class (options here being new JsonSerializerOptions(JsonSerializerDefaults.Web) for the camelCase keys). Under the hood compares both approaches with serde.

    r#"..."# is a raw string: backslashes and double quotes inside it are literal, which keeps JSON readable.r#"..."# is a raw string, like C#‘s """...""" raw string literals: double quotes inside it are literal. For JSON whose shape you don’t know in advance, serde_json::Value holds any JSON value, and the json! macro builds one from JSON-like syntax.

    Bad input is an error, not a surprise

    from_str returns a Result. If the JSON doesn’t match the struct, you get an Err that says what’s wrong and where:

    let inputs = [
        r#"{"orderId":"seven","customerName":"Grace","items":[]}"#,
        r#"{"orderId":7,"items":[]}"#,
        r#"{"orderId":7,"customerName":"Grace","items":[]"#,
    ];
    for json in inputs {
        match serde_json::from_str::<Order>(json) {
            Ok(order) => println!("parsed order {}", order.order_id),
            Err(error) => println!("rejected: {error}"),
        }
    }

    Output

    rejected: invalid type: string "seven", expected u32 at line 1 column 18
    rejected: missing field `customerName` at line 1 column 24
    rejected: EOF while parsing an object at line 1 column 46

    A field that isn’t an Option is required, and its type is checked, so once from_str returns Ok, every field holds a value of the right type. To fill in a missing field instead of failing, mark it #[serde(default)].

    With a plain JSON.parse and a type assertion, TypeScript checks nothing, and the bad data travels on:

    cast.ts
    type Order = { orderId: number; customerName: string; items: string[] };
    
    const order = JSON.parse('{"orderId":"seven","items":[]}') as Order;
    console.log(order.orderId + 1);
    console.log(order.customerName);

    Output

    seven1
    undefined

    That’s why TypeScript projects validate with hand-written checks, as in parseOrder above, or with a schema library such as Zod. serde gives you that check from the struct definition itself.

    System.Text.Json rejects a wrong type, but by default a missing property quietly gets its default value, even a non-nullable string:

    Missing.cs
    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    var order = JsonSerializer.Deserialize("""{"orderId":7,"items":[]}""", OrderJson.Default.Order)!;
    Console.WriteLine($"customerName is null: {order.CustomerName is null}");
    
    record Order(int OrderId, string CustomerName, List<string> Items);
    
    [JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
    [JsonSerializable(typeof(Order))]
    partial class OrderJson : JsonSerializerContext;

    Output

    customerName is null: True

    You can opt in to stricter checks with [JsonRequired] or the RespectRequiredConstructorParameters option. In serde, required is the default and optional is what you opt in to, with Option or #[serde(default)].

    Which one should I use?

    Macros are powerful, and the easiest code to read is the code that doesn’t need one. Reach for the simplest tool that does the job:

    WhatWhenWhyHow
    A functionThe logic works on known types with a fixed number of arguments. The default.Easiest to read, test and debug; the editor understands it fully.fn apply_discount(price: u32, percent: u32) -> u32
    A generic functionThe same logic should work for several types that share a trait.One definition, type-checked once against the bound.fn largest<T: PartialOrd>(items: &[T]) -> &T; Module 9 covers bounds.
    macro_rules!You need what a function can’t do: any number of arguments, the source text of an argument, or generating items such as several similar impl blocks.Expands to plain code at compile time, so it costs nothing at runtime.macro_rules! show { ($($value:expr),+) => { ... }; }
    A standard deriveYour type needs Debug, Clone, PartialEq, Default or another standard trait, done field by field.The compiler writes correct, consistent code and keeps it in sync when fields change.#[derive(Debug, Clone, PartialEq)]
    serde’s deriveYour type goes to or from JSON or another format.Generates the reading and writing code at compile time, with field checks and clear errors.#[derive(Serialize, Deserialize)], plus #[serde(...)] attributes for names and optional fields.
    A hand-written implThe derived behavior isn’t what you want, such as Debug that hides a password.You control every detail.impl fmt::Debug for User { ... }

    Rule of thumb: write a function first, and make it generic when a second type needs it. Derive the standard traits and serde’s traits instead of writing them by hand. Write a macro_rules! macro only for what a function can’t express, and keep it small.

    Function, generic, macro or derive?
    1. Does your type need a standard trait such as Debug, Clone or PartialEq, or serde's Serialize and Deserialize?

      Yes

      Derive it: #[derive(Debug, Serialize, Deserialize)]Write the impl by hand only when the derived behavior is wrong for the type.

      No
    2. Does the call need any number of arguments, the source text of an argument, or to generate items such as several impl blocks?

      Yes

      Write a macro_rules! macroKeep it small, and have it expand to calls to ordinary functions where it can.

      No
    3. Should the same logic work for several types?

      Yes

      Write a generic function with a trait boundFor example fn largest<T: PartialOrd>(items: &[T]) -> &T.

      No
    4. Otherwise: Write a plain function.

    Under the hood

    #[derive(Serialize)] is a procedural macro from the serde_derive crate. While your code compiles, it reads the struct’s tokens (its name, field names, types and #[serde] attributes) and writes an impl Serialize for Order. For a small struct, the generated code amounts to this:

    use serde::ser::{Serialize, SerializeStruct, Serializer};
    
    struct Point {
        x: i32,
        y: i32,
    }
    
    impl Serialize for Point {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut state = serializer.serialize_struct("Point", 2)?;
            state.serialize_field("x", &self.x)?;
            state.serialize_field("y", &self.y)?;
            state.end()
        }
    }
    
    fn main() -> Result<(), serde_json::Error> {
        println!("{}", serde_json::to_string(&Point { x: 1, y: 2 })?);
        Ok(())
    }

    Output

    {"x":1,"y":2}

    Notice what isn’t in it: anything about JSON. The impl describes the struct to a Serializer, and serde_json provides one that writes JSON. Other crates provide serializers for TOML, YAML, MessagePack and more, and the same derive works with all of them. Deserialize works the same way in reverse: the generated code matches each key to a field and asks that field’s type to read the value, which is where the “missing field” and “invalid type” errors you saw above come from.

    Because Serializer is a generic parameter, serde_json::to_string(&order) compiles into code specialized for Order and JSON: field names are string constants, and there’s no lookup of type information while the program runs. The binary carries no description of the struct’s fields, because Rust doesn’t keep one.

    TypeScript can’t work this way: its types are erased before the code runs, so there’s nothing left to generate from. Schema libraries such as Zod turn it around: you write the schema as a runtime value, and the type is inferred from it.
    This is the model the System.Text.Json source generator follows: it writes the serialization code at build time, which is why it works with trimming and native AOT. Reflection-based serialization doesn’t, so .NET 10 turns it off in file-based apps, which are set up for native AOT by default. That’s the only reason the C# examples on this page use the source generator: in an ordinary project, reflection-based JsonSerializer calls work as they always have.

    Common pitfalls

    Common pitfallForgetting the derive

    serde_json::to_string only accepts types that implement Serialize. Leave out the derive and the call doesn’t compile:

    struct Order {
        order_id: u32,
    }
    
    fn main() {
        let order = Order { order_id: 42 };
        println!("{}", serde_json::to_string(&order).unwrap());
    }

    Rust doesn't compile this: error E0277

    error[E0277]: the trait bound `Order: serde::Serialize` is not satisfied
        --> main.rs:7:42
         |
       7 |     println!("{}", serde_json::to_string(&order).unwrap());
         |                    --------------------- ^^^^^^ unsatisfied trait bound
         |                    |
         |                    required by a bound introduced by this call
         |
    help: the trait `serde_core::ser::Serialize` is not implemented for `Order`
        --> main.rs:1:1
         |
       1 | struct Order {
         | ^^^^^^^^^^^^
         = note: for local types consider adding `#[derive(serde::Serialize)]` to your `Order` type
         = note: for types from other crates check whether the crate offers a `serde` feature flag
         = help: the following other types implement trait `serde_core::ser::Serialize`:
                   &'a T
                   &'a mut T
                   ()
                   (T,)
                   (T0, T1)
                   (T0, T1, T2)
                   (T0, T1, T2, T3)
                   (T0, T1, T2, T3, T4)
                 and 129 others
    note: required by a bound in `serde_json::to_string`
         |
         | pub fn to_string<T>(value: &T) -> Result<String>
         |        --------- required by a bound in this function
         | where
         |     T: ?Sized + Serialize,
         |                 ^^^^^^^^^ required by this bound in `to_string`

    Add #[derive(Serialize)] (and use serde::Serialize;). If the compiler then says it can’t find the derive macro Serialize, the derive feature is missing from serde in Cargo.toml.

    Common pitfallsnake_case fields, camelCase JSON

    Without rename_all, serde uses the Rust field names as they are, so camelCase JSON doesn’t match:

    use serde::Deserialize;
    
    #[derive(Debug, Deserialize)]
    struct Order {
        order_id: u32,
    }
    
    fn main() {
        let result = serde_json::from_str::<Order>(r#"{"orderId":7}"#);
        if let Err(error) = result {
            println!("{error}");
        }
    }

    Output

    missing field `order_id` at line 1 column 13

    Add #[serde(rename_all = "camelCase")] to the struct, or #[serde(rename = "orderId")] to one field.

    Common pitfallUnknown keys are ignored

    By default, serde skips keys the struct doesn’t have. Combined with an Option field, a misspelled key such as "coupon_code" instead of "couponCode" gives you None without an error. If unexpected keys should be an error, add #[serde(deny_unknown_fields)] to the struct.

    Common pitfallA macro where a function would do

    A macro’s errors point into its expansion, your editor understands it less well, and readers have to learn its syntax. If a function or a generic function can do the job, use that. Macros are for what functions can’t express.

    Try it yourself

    Exercise: port this to Rust

    Port this settings loader to Rust with serde. The JSON keys are camelCase. theme is optional in the input and defaults to light, and when the settings are written back, theme is always included.

    Starting code in TypeScript
    settings.ts
    type Settings = { appName: string; maxItems: number; theme: string };
    
    function parseSettings(json: string): Settings {
      const { appName, maxItems, theme = "light" } = JSON.parse(json) as Record<string, unknown>;
      if (typeof appName !== "string" || typeof maxItems !== "number" || typeof theme !== "string") {
        throw new Error("invalid settings");
      }
      return { appName, maxItems, theme };
    }
    
    const inputs = ['{"appName":"shelf","maxItems":20}', '{"appName":"shelf","maxItems":50,"theme":"dark"}'];
    for (const json of inputs) {
      const settings = parseSettings(json);
      console.log(`${settings.appName}: ${settings.maxItems} items, ${settings.theme} theme`);
    }
    
    const defaults: Settings = { appName: "shelf", maxItems: 10, theme: "light" };
    console.log(JSON.stringify(defaults));
    Starting code in C#
    Settings.cs
    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    string[] inputs =
    [
        """{"appName":"shelf","maxItems":20}""",
        """{"appName":"shelf","maxItems":50,"theme":"dark"}""",
    ];
    foreach (var json in inputs)
    {
        var settings = JsonSerializer.Deserialize(json, SettingsJson.Default.Settings)!;
        Console.WriteLine($"{settings.AppName}: {settings.MaxItems} items, {settings.Theme} theme");
    }
    
    var defaults = new Settings("shelf", 10);
    Console.WriteLine(JsonSerializer.Serialize(defaults, SettingsJson.Default.Settings));
    
    record Settings(string AppName, int MaxItems, string Theme = "light");
    
    [JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
    [JsonSerializable(typeof(Settings))]
    partial class SettingsJson : JsonSerializerContext;

    Expected output

    shelf: 20 items, light theme
    shelf: 50 items, dark theme
    {"appName":"shelf","maxItems":10,"theme":"light"}
    Show a hint

    Derive Serialize and Deserialize, add rename_all = camelCase, and give theme the attribute #[serde(default = ...)] naming a function that returns the String light. A missing theme then reads as light, and to_string writes it out.

    Show a solution
    use serde::{Deserialize, Serialize};
    
    #[derive(Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct Settings {
        app_name: String,
        max_items: u32,
        #[serde(default = "default_theme")]
        theme: String,
    }
    
    fn default_theme() -> String {
        String::from("light")
    }
    
    fn main() -> Result<(), serde_json::Error> {
        let inputs = [
            r#"{"appName":"shelf","maxItems":20}"#,
            r#"{"appName":"shelf","maxItems":50,"theme":"dark"}"#,
        ];
        for json in inputs {
            let settings: Settings = serde_json::from_str(json)?;
            println!(
                "{}: {} items, {} theme",
                settings.app_name, settings.max_items, settings.theme
            );
        }
    
        let defaults = Settings {
            app_name: String::from("shelf"),
            max_items: 10,
            theme: default_theme(),
        };
        println!("{}", serde_json::to_string(&defaults)?);
        Ok(())
    }

    The serde default attribute, with the function name default_theme as a string, calls default_theme when the key is missing, so theme is a plain String, not an Option, and the rest of the code never has to handle a missing value. rename_all maps app_name and max_items to appName and maxItems in both directions, and main returns Result so ? can pass a parse error up.

    Saved in this browser only.