Custom Serialization
Field attributes.
Custom Serialization is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Customizing serde
serde gives fine control over how fields map to a format using attributes. You rename fields, skip them, set defaults, and more, all via #[serde(...)].
Renaming a field
Use rename to map a Rust field name to a different key in the output, useful when JSON uses a different convention.
use serde::Serialize;
#[derive(Serialize)]
struct User {
#[serde(rename = "userName")]
user_name: String,
}Renaming everything
Apply a naming convention to all fields at once with rename_all, e.g. snake_case Rust to camelCase JSON.
use serde::Serialize;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct User {
first_name: String,
last_name: String,
}Skipping fields
skip omits a field entirely. skip_serializing_if omits it conditionally, like hiding empty options.
use serde::Serialize;
#[derive(Serialize)]
struct User {
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
nickname: Option<String>,
}Default values on deserialize
default supplies a value when a field is missing from the input, so deserialization does not fail.
use serde::Deserialize;
#[derive(Deserialize)]
struct Config {
#[serde(default)]
retries: u32,
}Custom default function
Point default at a function to provide a non-zero fallback value.
use serde::Deserialize;
fn default_port() -> u16 { 8080 }
#[derive(Deserialize)]
struct Config {
#[serde(default = "default_port")]
port: u16,
}Modeling rename + default
The attribute logic is just key mapping plus fallback. This runnable example mirrors that behavior with a HashMap.
use std::collections::HashMap;
fn main() {
let mut input: HashMap<&str, &str> = HashMap::new();
input.insert("userName", "Alice");
let user_name = input.get("userName").copied().unwrap_or("anon");
let port = input.get("port").copied().unwrap_or("8080");
println!("user_name={} port={}", user_name, port);
}Aliases on deserialize
alias accepts an alternative key when reading, helpful when supporting both old and new field names.
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
#[serde(alias = "username")]
name: String,
}Flatten
flatten inlines a nested struct's fields into the parent object, removing one level of nesting in the JSON.
use serde::Serialize;
#[derive(Serialize)]
struct Meta { page: u32 }
#[derive(Serialize)]
struct Resp {
data: String,
#[serde(flatten)]
meta: Meta,
}Custom with module
For full control, point with at a module exposing serialize and deserialize functions, e.g. to format a timestamp.
use serde::Serialize;
#[derive(Serialize)]
struct Event {
#[serde(with = "my_date_format")]
at: i64,
}Enum tagging
Control how enums encode with tag (internally tagged) or untagged. This shapes the JSON for variant types.
use serde::Serialize;
#[derive(Serialize)]
#[serde(tag = "type")]
enum Event {
Click { x: i32, y: i32 },
Key { code: u8 },
}Quick Check
Test your understanding of custom serialization.
Recap
You learned to customize serialization:
renameandrename_allmap field namesskip,skip_serializing_ifcontrol outputdefaultandaliasease deserializationflatten,with, and enumtaghandle shape
Next: formats beyond JSON.
Frequently asked questions
Is the “Custom Serialization” lesson free?
Yes — the full text of “Custom Serialization” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Custom Serialization”?
Field attributes. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Custom Serialization” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Serialize and Deserialize
- Working with JSON
- Custom Serialization
- Other Formats