Debian Codegraph @

third_party/rust/serde_with/src/guide.md

raw
1 # `serde_with` User Guide
2
3 This crate provides helper functions to extend and change how [`serde`] serializes different data types.
4 For example, you can serialize [a map as a sequence of tuples][crate::guide::serde_as#maps-to-vec-of-tuples], serialize [using the `Display` and `FromStr` traits][`DisplayFromStr`], or serialize [an empty `String` like `None`][NoneAsEmptyString].
5 `serde_with` covers types from the Rust Standard Library and some common crates like [`chrono`][serde_with_chrono].
6
7 [**A list of all supported transformations is available on this page.**](crate::guide::serde_as_transformations)
8
9 The crate offers four types of functionality.
10
11 ## 1. A more flexible and composable replacement for the `with` annotation, called `serde_as`
12
13 This is an alternative to [serde's `with` annotation][with-annotation], which adds flexibility and composability to the scheme.
14 The main downside is that it works with fewer types than [`with` annotations][with-annotation].
15 However, all types from the Rust Standard Library should be supported in all combinations and any missing entry is a bug.
16
17 You mirror the type structure of the field you want to de/serialize.
18 You can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`.
19 The default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`.
20
21 The `serde_as` scheme is based on two new traits: [`SerializeAs`] and [`DeserializeAs`].
22 [Check out the detailed page about `serde_as` and the available features.](crate::guide::serde_as)
23
24 ### Example
25
26 ```rust
27 # use serde::{Deserialize, Serialize};
28 # use serde_with::{serde_as, DisplayFromStr, Map};
29 # use std::net::Ipv4Addr;
30 #
31 #[serde_as]
32 # #[derive(Debug, PartialEq, Eq)]
33 #[derive(Deserialize, Serialize)]
34 struct Data {
35 // Type does not implement Serialize or Deserialize
36 #[serde_as(as = "DisplayFromStr")]
37 address: Ipv4Addr,
38 // Treat the Vec like a map with duplicates
39 // Convert u32 into a String and keep the String the same type
40 #[serde_as(as = "Map<DisplayFromStr, _>")]
41 vec_as_map: Vec<(u32, String)>,
42 }
43
44 let data = Data {
45 address: Ipv4Addr::new(192, 168, 0, 1),
46 vec_as_map: vec![
47 (123, "Hello".into()),
48 (456, "World".into()),
49 (123, "Hello".into()),
50 ],
51 };
52
53 let json = r#"{
54 "address": "192.168.0.1",
55 "vec_as_map": {
56 "123": "Hello",
57 "456": "World",
58 "123": "Hello"
59 }
60 }"#;
61
62 // Test Serialization
63 assert_eq!(json, serde_json::to_string_pretty(&data).unwrap());
64 // Test Deserialization
65 assert_eq!(data, serde_json::from_str(json).unwrap());
66 ```
67
68 ## 2. proc-macros to make it easier to use both above parts
69
70 The proc-macros are an optional addition and improve the user experience for common tasks.
71 We have already seen how the `serde_as` attribute is used to define the serialization instructions.
72
73 The proc-macro attributes are defined in the [`serde_with_macros`] crate and re-exported from the root of this crate.
74 The proc-macros are optional, but enabled by default.
75 For further details, please refer to the documentation of each proc-macro.
76
77 ## 3. Derive macros to implement `Deserialize` and `Serialize`
78
79 The derive macros work similar to the serde provided ones, but they do implement other de/serialization schemes.
80 For example, the derives [`DeserializeFromStr`] and [`SerializeDisplay`] require that the type also implement [`FromStr`] and [`Display`] and de/serializes from/to a string instead of the usual way of iterating over all fields.
81
82 [`Display`]: std::fmt::Display
83 [`FromStr`]: std::str::FromStr
84 [`serde_with_macros`]: serde_with_macros
85 [serde_with_chrono]: crate::chrono
86 [with-annotation]: https://serde.rs/field-attrs.html#with