patternrustTip
serde: serializing and deserializing Rust types to JSON
Viewed 0 times
serdeJSONserializedeserializerename_allskip_serializing_ifserde_json
Error Messages
Problem
Converting Rust structs to and from JSON requires significant boilerplate without a library, and getting field naming conventions right is tricky.
Solution
Add serde and serde_json to Cargo.toml, derive Serialize/Deserialize, and use serde attributes for customization:
# Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] // snake_case fields -> camelCase JSON
struct ApiResponse {
user_id: u64,
display_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
avatar_url: Option<String>,
#[serde(default)]
is_active: bool,
}
let json = r#"{"userId":42,"displayName":"Alice"}"#;
let resp: ApiResponse = serde_json::from_str(json).unwrap();
println!("{:?}", resp);
let serialized = serde_json::to_string_pretty(&resp).unwrap();
println!("{}", serialized);Why
Serde is a zero-overhead serialization framework — the derive macros generate specialized code at compile time rather than using runtime reflection, making it faster than most alternatives in other languages.
Gotchas
- serde_json::Value is an untyped representation useful for dynamic JSON but loses type safety
- #[serde(flatten)] merges a nested struct's fields into the parent JSON object
- Enums serialize as {"VariantName": {...}} by default — use #[serde(tag = "type")] for tagged union style
Revisions (0)
No revisions yet.