Rust

Differentiating Missing and Null Fields in Serde

JSON APIs frequently treat missing fields and explicit null fields as completely different intents, especially in PATCH endpoints. In Rust, deserializing either payload into an Option<Option<T>> with standard Serde attributes either flattens them into the same value or throws an unhelpful runtime deserialization error.

Here is the exact issue. You write an update endpoint where an omitted field means “leave this field alone”, an explicit null means “clear this field to NULL in the database”, and a raw value means “update this field”.

The Broken Default State

Consider this typical payload struct using standard Serde derives:

rust
use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
pub struct PatchUserPayload {
    #[serde(default)]
    pub nickname: Option<Option<String>>,
}

Now test it against the three common JSON inputs:

rust
#[test]
fn test_patch_payload() {
    let missing = r#"{}"#;
    let explicit_null = r#"{"nickname": null}"#;
    let explicit_value = r#"{"nickname": "alex"}"#;

    let res_missing: PatchUserPayload = serde_json::from_str(missing).unwrap();
    let res_null: PatchUserPayload = serde_json::from_str(explicit_null).unwrap();
    let res_value: PatchUserPayload = serde_json::from_str(explicit_value).unwrap();

    println!("missing: {:?}", res_missing);
    println!("null: {:?}", res_null);
    println!("value: {:?}", res_value);
}

Run cargo test. The test fails during deserialization of the explicit null:

text
thread 'test_patch_payload' panicked at src/main.rs:13:67:
called `Result::unwrap()` on an `Err` value: Error("invalid type: null, expected a string", line: 1, column: 17)

If you instead use Option<T> with #[serde(default)], the error disappears, but both payloads produce identical Rust output:

text
missing: PatchUserPayload { nickname: None }
null: PatchUserPayload { nickname: None }
value: PatchUserPayload { nickname: Some("alex") }

Your backend cannot tell whether the client sent {} or {"nickname": null}. You cannot safely issue a SQL UPDATE users SET nickname = NULL without accidentally wiping out the nickname of every user submitted through a partial update form.

Why Serde Fails on Option<Option<T>>

Serde does not have a native concept of tri-state presence in its data model. Its data model has Option<T>, which maps directly to the presence or absence of a value, but Option implements Visitor::visit_none and Visitor::visit_unit by resolving to None.

When Serde parses {"nickname": null}, the outer field nickname is found in the map. Serde hands the inner parser the type Option<Option<String>>. Because Option<T> has special-case handling inside serde_json, encountering null immediately resolves the outermost Option to None. It does not recurse into the inner Option.

Conversely, when nickname is omitted entirely, the field is missing from the JSON object. The #[serde(default)] attribute steps in and invokes Default::default(), which also produces None.

Both paths collapse into None. When you nest Option<Option<T>>, the inner deserializer expects either missing or a string. It gets null at the second layer and throws the invalid type: null, expected a string error.

The Fix: A Tri-State Field Visitor

To differentiate missing, null, and present values reliably, you need an enum that cleanly represents all three states, combined with a custom deserializer function.

Add this enum and deserialization helper to your codebase:

rust
use serde::{Deserialize, Deserializer, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum UpdateField<T> {
    Missing,
    Null,
    Value(T),
}

impl<T> Default for UpdateField<T> {
    fn default() -> Self {
        UpdateField::Missing
    }
}

pub fn deserialize_update_field<'de, D, T>(deserializer: D) -> Result<UpdateField<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    Deserialize::deserialize(deserializer).map(|opt: Option<T>| match opt {
        Some(val) => UpdateField::Value(val),
        None => UpdateField::Null,
    })
}

Now apply this helper to your struct:

rust
use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
pub struct PatchUserPayload {
    #[serde(default, deserialize_with = "deserialize_update_field")]
    pub nickname: UpdateField<String>,
    
    #[serde(default, deserialize_with = "deserialize_update_field")]
    pub age: UpdateField<u32>,
}

How this works:

  1. If the key nickname is completely absent from the JSON payload, Serde skips the deserialize_with function entirely and executes Default::default(). This produces UpdateField::Missing.
  2. If nickname is present with a value of null, Serde runs deserialize_update_field. The inner call deserializes Option<T>. Since JSON null maps to None, the closure matches None and returns UpdateField::Null.
  3. If nickname is present with "alex", the inner call yields Some("alex"). The closure matches Some(val) and returns UpdateField::Value("alex".to_string()).

Verifying the Solution

Run a unit test covering all three states:

rust
#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_patch_field_distinction() {
        let missing_json = json!({});
        let null_json = json!({ "nickname": null });
        let value_json = json!({ "nickname": "alex" });

        let parsed_missing: PatchUserPayload = serde_json::from_value(missing_json).unwrap();
        let parsed_null: PatchUserPayload = serde_json::from_value(null_json).unwrap();
        let parsed_value: PatchUserPayload = serde_json::from_value(value_json).unwrap();

        assert_eq!(parsed_missing.nickname, UpdateField::Missing);
        assert_eq!(parsed_null.nickname, UpdateField::Null);
        assert_eq!(parsed_value.nickname, UpdateField::Value("alex".to_string()));
    }
}

Run the tests:

bash
cargo test test_patch_field_distinction -- --nocapture

The test passes cleanly:

text
running 1 test
test tests::test_patch_field_distinction ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Gotcha 1: Interaction with Internally Tagged Enums

If you wrap this struct inside an internally tagged Serde enum, your deserialization logic will fail silently or reject valid input.

Consider this design:

rust
#[derive(Debug, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum Command {
    UpdateUser(PatchUserPayload),
    DeleteUser { user_id: u64 },
}

Try parsing this payload:

rust
let payload = r#"{"action": "update_user", "nickname": null}"#;
let cmd: Result<Command, _> = serde_json::from_str(payload);

This throws an error:

text
Err(Error("invalid type: map, expected a string", line: 1, column: 44))

Internally tagged enums (#[serde(tag = "...")]) work by buffering the entire JSON object into an internal Content intermediate representation. Serde parses the fields twice: once to find the tag, and once to deserialize the content into your target struct.

During the buffering step, Serde’s internal representation normalizes untagged shapes, stripping the distinction between missing fields and null fields on custom visitors.

If you must use tagged payloads with tri-state fields, switch to an adjacently tagged enum:

rust
#[derive(Debug, Deserialize)]
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
pub enum Command {
    UpdateUser(PatchUserPayload),
    DeleteUser { user_id: u64 },
}

The JSON representation becomes:

json
{
  "type": "update_user",
  "payload": {
    "nickname": null
  }
}

Because payload is parsed directly as an isolated object rather than an open-ended map containing the sibling action tag, deserialize_update_field receives raw parser events and preserves the difference between missing and null.

Gotcha 2: Workspace Feature Unification Masquerading as Serde Bugs

You will sometimes see UpdateField work in your unit tests within a sub-crate, but fail when compiled as part of your main web service binary. This happens when another crate in your Cargo workspace enables a serde feature globally.

If crate api-types defines your models with minimal dependencies:

toml
# crates/api-types/Cargo.toml
[dependencies]
serde = { version = "1.0", default-features = false, features = ["alloc"] }
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }

And your database worker crate imports serde_json with the arbitrary_precision feature:

toml
# crates/db-worker/Cargo.toml
[dependencies]
serde_json = { version = "1.0", features = ["arbitrary_precision"] }

Cargo unifies features across the entire dependency graph for the same package version. When you compile the workspace via cargo test --workspace or build the final binary, serde_json is compiled with arbitrary_precision for all crates.

With arbitrary_precision enabled, numbers are no longer deserialized into primitive types (i64, f64) directly during generic visitor dispatch. They are converted into an internal Number struct.

If your UpdateField<T> wraps numeric fields or generic values parsed through untagged enums, standard visitor fallbacks like visit_u64 will stop being called in favor of visit_map holding an internal number representation.

To detect if feature unification is altering your Serde deserialization pipeline, inspect the resolved feature tree:

bash
cargo tree --duplicates
cargo tree -e features -i serde_json

The output highlights where unified flags originate:

text
serde_json v1.0.117
├── serde_json feature "arbitrary_precision"
│   └── db-worker v0.1.0
│       └── backend v0.1.0
└── serde_json feature "default"
    └── api-types v0.1.0

If feature unification causes deserialization differences in edge crates, run your tests with feature isolation using cargo’s resolver v2 in your root Cargo.toml:

toml
[workspace]
resolver = "2"
members = [
    "crates/api-types",
    "crates/db-worker",
    "crates/backend",
]

Resolver v2 prevents dev-dependencies from enabling features on normal build dependencies, avoiding cases where running cargo test in the root workspace silently alters parsing behavior compared to running cargo run --bin backend.

Practical Database Mapping

To consume UpdateField<T> in your persistence layer without boilerplate match arms, implement a helper that maps to your database client’s query builder.

rust
impl<T> UpdateField<T> {
    pub fn as_ref(&self) -> UpdateField<&T> {
        match self {
            UpdateField::Missing => UpdateField::Missing,
            UpdateField::Null => UpdateField::Null,
            UpdateField::Value(val) => UpdateField::Value(val),
        }
    }

    pub fn is_missing(&self) -> bool {
        matches!(self, UpdateField::Missing)
    }
}

In your repository layer, translate this state to your query parameters:

rust
pub fn apply_user_update(user_id: i64, patch: &PatchUserPayload) -> (String, Vec<String>) {
    let mut query = String::from("UPDATE users SET ");
    let mut assignments = Vec::new();

    match &patch.nickname {
        UpdateField::Missing => {
            // Field omitted from request: do not add to SET clause
        }
        UpdateField::Null => {
            assignments.push("nickname = NULL".to_string());
        }
        UpdateField::Value(name) => {
            assignments.push(format!("nickname = '{name}'"));
        }
    }

    match &patch.age {
        UpdateField::Missing => {}
        UpdateField::Null => {
            assignments.push("age = NULL".to_string());
        }
        UpdateField::Value(age) => {
            assignments.push(format!("age = {age}"));
        }
    }

    query.push_str(&assignments.join(", "));
    query.push_str(&format!(" WHERE id = {user_id};"));
    (query, assignments)
}

Now {} generates no updates, {"nickname": null} writes a SQL NULL, and {"nickname": "alex"} writes the string literal. The compiler forces handling of all three variants.

More in Rust