Rust Serde: JSON Serialization, Derive Macros, and Field Attributes
Serde attributes decide the wire format: rename strategies, defaults, flatten, enum tags and custom codecs, plus the number and ordering traps.

Quick Summary
Serde is a serialization framework, not a JSON library. Types implement Serialize and Deserialize once, and any format crate — serde_json, serde_yaml, bincode, toml, postcard — can then read and write them. The derive feature generates those implementations from struct and enum definitions, and attributes adjust the wire format without touching the types' logic.
The attributes fall into two groups. Container attributes (rename_all, deny_unknown_fields, tag, transparent, default) describe the type as a whole. Field attributes (rename, skip, skip_serializing_if, default, flatten, with, borrow) describe individual members. Most production schema drift is fixed with #[serde(rename_all = "camelCase")] and #[serde(alias = "...")].
serde_json adds the dynamic side: Value for untyped data, the json! macro for literals, and to_value/from_value to move between typed and untyped worlds. Precision loss, key ordering, and number representation are the three places where "it round-trips" quietly stops being true.
Basic Syntax & Signature
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct User {
user_id: u64,
#[serde(rename = "displayName")]
display_name: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
email: Option<String>,
#[serde(default = "default_role")]
role: Role,
#[serde(skip)]
internal_cache: Vec<u8>,
}
fn default_role() -> Role { Role::Reader }
#[derive(Debug, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
enum Role {
#[default]
Reader,
Writer,
Admin,
}
fn main() -> Result<(), serde_json::Error> {
let user = User {
user_id: 7,
display_name: "Ada".into(),
email: None,
role: Role::Writer,
internal_cache: vec![1, 2, 3],
};
let json = serde_json::to_string(&user)?;
// {"userId":7,"displayName":"Ada","role":"writer"}
assert_eq!(json, r#"{"userId":7,"displayName":"Ada","role":"writer"}"#);
// Round trip through a typed value.
let back: User = serde_json::from_str(&json)?;
assert_eq!(back, user);
// Dynamic value, then back to a type.
let mut value = serde_json::to_value(&user)?;
value["role"] = serde_json::json!("admin");
let promoted: User = serde_json::from_value(value)?;
assert_eq!(promoted.role, Role::Admin);
Ok(())
}Core API surface:
// serde_json
pub fn to_string<T: ?Sized + Serialize>(value: &T) -> Result<String>;
pub fn to_string_pretty<T: ?Sized + Serialize>(value: &T) -> Result<String>;
pub fn to_vec<T: ?Sized + Serialize>(value: &T) -> Result<Vec<u8>>;
pub fn from_str<'a, T: Deserialize<'a>>(s: &'a str) -> Result<T>;
pub fn from_slice<'a, T: Deserialize<'a>>(v: &'a [u8]) -> Result<T>;
pub fn to_value<T: ?Sized + Serialize>(value: &T) -> Result<Value>;
pub fn from_value<T: DeserializeOwned>(value: Value) -> Result<T>;
// serde traits, implemented by derive
pub trait Serialize { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error>; }
pub trait Deserialize<'de>: Sized { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error>; }DeserializeOwned is a blanket alias for for<'de> Deserialize<'de> — the form you need whenever the value cannot borrow from the input, as with from_value and from_reader.
Key Comparison Table
| Attribute | Applies to | Effect | Typical use |
|---|---|---|---|
rename | field, variant | Changes the wire name | Snake to camel |
rename_all | container | Applies a case convention to all names | API payloads |
alias | field, variant | Accepts extra names on deserialize | Schema migration |
skip | field, variant | Neither serialize nor deserialize | Caches, handles |
skip_serializing | field | Write-only omission | Internal flags |
skip_deserializing | field | Read-only omission | Defaults |
skip_serializing_if = "path" | field | Conditional omission | Option::is_none |
default / default = "path" | field, container | Missing field fallback | Backward compatibility |
flatten | field | Inlines a struct's fields | Shared metadata blocks |
deny_unknown_fields | container | Errors on extra keys | Strict configs |
tag = "type" | enum | Internally tagged | JSON discriminator |
tag + content | enum | Adjacently tagged | Readable enum JSON |
untagged | enum | No tag; matches by shape | Union-like payloads |
transparent | newtype | Delegates to the inner type | Newtype wrappers |
with / serialize_with | field | Custom codec functions | Dates, decimals |
borrow | field | Zero-copy from input | &'a str fields |
| Enum representation | JSON shape | Caution |
|---|---|---|
| External (default) | {"Variant":{"x":1}} | Verbose, but always works |
Internal tag | {"type":"Variant","x":1} | Cannot hold tuple variants |
Adjacent tag+content | {"type":"Variant","content":{"x":1}} | Verbose but universal |
| Untagged | {"x":1} | No error message when nothing matches |
Practical Edge Cases & Deep Dives
1. flatten for shared metadata
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
struct Envelope {
id: String,
#[serde(flatten)]
meta: Meta,
#[serde(flatten)]
extra: HashMap<String, serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Meta {
created_at: String,
version: u32,
}
fn main() -> Result<(), serde_json::Error> {
let input = r#"{
"id": "a1",
"created_at": "2026-01-01T00:00:00Z",
"version": 2,
"region": "eu"
}"#;
let env: Envelope = serde_json::from_str(input)?;
assert_eq!(env.meta.version, 2);
assert_eq!(env.extra["region"], serde_json::json!("eu"));
Ok(())
}flatten with a HashMap<String, Value> catch-all is the standard way to accept forward-compatible payloads without deny_unknown_fields. Two constraints: flatten needs a self-describing format (it fails on bincode), and it disables deny_unknown_fields on the containing struct because unknown keys are swallowed by the catch-all.
2. Rename strategies and aliases for schema migration
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum Event { UserCreated, UserDeleted }
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
struct Account {
account_id: u32,
// Accept the old snake_case key during the migration window.
#[serde(alias = "display_name", alias = "name")]
display_name: String,
// Serialize an explicit null even though the field is Option.
#[serde(default)]
plan: Option<String>,
}
fn main() -> Result<(), serde_json::Error> {
assert_eq!(serde_json::to_string(&Event::UserCreated)?, r#""USER_CREATED""#);
let old = r#"{"accountId":1,"display_name":"Ada"}"#;
let acct: Account = serde_json::from_str(old)?;
assert_eq!(acct.display_name, "Ada");
assert_eq!(acct.plan, None);
// Note: with `default` and no skip_serializing_if, the field is written as null.
assert_eq!(
serde_json::to_string(&acct)?,
r#"{"accountId":1,"displayName":"Ada","plan":null}"#
);
Ok(())
}rename_all accepts lowercase, UPPERCASE, PascalCase, camelCase, snake_case, SCREAMING_SNAKE_CASE, and kebab-case. For enums it also has rename_all_fields to rename the fields of every variant's struct. Aliases are deserialize-only: they are never emitted.
3. Custom (de)serialization for a value type
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Debug, PartialEq)]
struct Seconds(u64);
impl Serialize for Seconds {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&format!("{}s", self.0))
}
}
impl<'de> Deserialize<'de> for Seconds {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.strip_suffix('s')
.ok_or_else(|| serde::de::Error::custom("expected a suffix 's'"))?
.parse::<u64>()
.map(Seconds)
.map_err(serde::de::Error::custom)
}
}
fn main() -> Result<(), serde_json::Error> {
let json = serde_json::to_string(&Seconds(30))?;
assert_eq!(json, r#""30s""#);
let back: Seconds = serde_json::from_str(&json)?;
assert_eq!(back, Seconds(30));
assert!(serde_json::from_str::<Seconds>(r#""30""#).is_err());
Ok(())
}The #[serde(with = "module")] form is the same code packaged as a pair of free functions named serialize and deserialize, which keeps the type's own Serialize free for other representations. A field-level with also works on a third-party type you cannot implement traits for.
4. Numbers: the precision traps
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Money {
// JSON numbers are IEEE-754 doubles in JavaScript, so 2^53 is the limit
// for lossless interchange with a JS client.
minor_units: i64,
#[serde(with = "rust_decimal_f64")]
rate: f64,
}
mod rust_decimal_f64 {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(v: &f64, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&format!("{v:.6}"))
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
let s = String::deserialize(d)?;
s.parse::<f64>().map_err(serde::de::Error::custom)
}
}
fn main() -> Result<(), serde_json::Error> {
// i64::MAX does not survive a round trip through a JSON number in JS,
// but serde_json itself keeps i64 exactly.
let big = i64::MAX;
let json = serde_json::to_string(&big)?;
assert_eq!(json, "9223372036854775807");
let back: i64 = serde_json::from_str(&json)?;
assert_eq!(back, big);
// A float is written with the shortest representation that round-trips,
// so `with` above is what pins it to six decimals on the wire.
let m = Money { minor_units: 1999, rate: 0.075 };
let out = serde_json::to_string(&m)?;
assert!(out.contains(r#""0.075000""#));
Ok(())
}serde_json maps JSON integers to i64/u64 and everything with a fraction or exponent to f64. A u128 larger than u64::MAX can be written as digits, but reading it back into a serde_json::Value loses it unless the arbitrary_precision feature is on, so identifiers that exceed 64 bits belong in strings — the same conclusion the JavaScript ecosystem reached with snowflake IDs.
5. Untagged enums and the ambiguity they hide
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(untagged)]
enum Payload {
Text { text: String },
Count { count: u64 },
Empty,
}
fn main() -> Result<(), serde_json::Error> {
let a: Payload = serde_json::from_str(r#"{"text":"hi"}"#)?;
assert_eq!(a, Payload::Text { text: "hi".into() });
let b: Payload = serde_json::from_str(r#"{"count":3}"#)?;
assert_eq!(b, Payload::Count { count: 3 });
// Order matters: a struct variant with all-optional fields would swallow
// other shapes, and `Empty` (a unit variant) matches any object.
let c: Payload = serde_json::from_str("{}")?;
assert_eq!(c, Payload::Empty);
// Failure messages are unhelpful: "data did not match any variant".
assert!(serde_json::from_str::<Payload>(r#"{"count":"three"}"#).is_err());
Ok(())
}Untagged enums try variants in declaration order and report only that nothing matched. They also cannot be used with flatten reliably, and they lose the ability to distinguish variants that share a shape. When error quality matters, an internally tagged enum with an explicit type field is the better design; when interoperating with a third-party schema you do not control, untagged is often the only option.
Common Compilation/Runtime Mistakes
| Error / symptom | Cause | Fix |
|---|---|---|
the trait bound 'T: Serialize' is not satisfied | derive feature missing or the derive not on the type | serde = { version = "1", features = ["derive"] } |
missing field 'x' | Required field absent in input | #[serde(default)] or Option<T> |
unknown field 'x', expected ... | deny_unknown_fields set | Remove it, or add the field |
invalid type: string, expected u64 | Wire type mismatch | #[serde(deserialize_with)], or a newtype |
Serialized key is "field_name" but API wants camelCase | No rename strategy | #[serde(rename_all = "camelCase")] |
key must be a string on HashMap<u32, T> | JSON object keys must be strings | Serialize as a list of pairs, or stringify keys |
flatten fails on bincode | Non-self-describing format | Keep flatten for JSON/TOML only |
data did not match any variant of untagged enum | No variant fits, or wrong order | Add type tag, or reorder variants |
Option<T> field omitted on output | skip_serializing_if present | Remove it if nulls are expected |
Deserializing &str from from_reader fails | Buffer is dropped; needs owned data | Use String or DeserializeOwned |
The one that costs the most time in production: serde_json::Value maps use BTreeMap by default, so key order is sorted, not insertion order. Comparing against a golden file with a different order fails even though the content matches — enable the preserve_order feature (backed by IndexMap) or compare parsed values rather than strings.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.