Serde is a generic Rust framework for serializing and deserializing data structures. It separates the data model from formats such as JSON, while format-specific crates provide the bridge. section 6.3
Serde centers on two complementary traits and an ecosystem of format adapters:
- Serialize renders a Rust data type into a chosen data format. section 6.3
- Deserialize parses a data format into a Rust data type. section 6.3
- serde_json connects Serde’s generic model to JSON; the ecosystem supports many other formats. section 6.3
- The derive feature lets the compiler generate trait implementations for structs through attributes such as #[derive(serde::Deserialize)]. section 6.3 section 6.7
Parsing JSON into a struct
Define a matching Rust type, derive Debug and Deserialize, and provide the expected type to serde_json::from_str: let parsed: Data = serde_json::from_str(input).unwrap();. A JSON object such as { "name": "Sharpe Oliver", "value": 134087 } becomes Data { name: "Sharpe Oliver", value: 134087 }. A mismatched field type produces an error; unwrapping that error panics rather than returning a parsed value.
Figure 6.1 The Serde ecosystem
Use the ecosystem diagram to see how Serde’s generic traits connect Rust data structures with format-specific crates. section 6.3
Serde also supports JavaScript interoperability through serde_wasm_bindgen: convert a JsValue into a Rust struct, run the operation, and encode the result back into JSON-compatible data. section 9.3.2
