| 1 |
# Custom de/serialization functions for Rust's [serde](https://serde.rs) |
| 2 |
|
| 3 |
[](https://crates.io/crates/serde_with/) |
| 4 |
[](https://github.com/jonasbb/serde_with) |
| 5 |
[](https://codecov.io/gh/jonasbb/serde_with) |
| 6 |
[](https://bestpractices.coreinfrastructure.org/projects/4322) |
| 7 |
[](https://www.rustexplorer.com/b/py7ida) |
| 8 |
|
| 9 |
--- |
| 10 |
|
| 11 |
This crate provides custom de/serialization helpers to use in combination with [serde's `with` annotation][with-annotation] and with the improved [`serde_as`][as-annotation]-annotation. |
| 12 |
Some common use cases are: |
| 13 |
|
| 14 |
* De/Serializing a type using the `Display` and `FromStr` traits, e.g., for `u8`, `url::Url`, or `mime::Mime`. |
| 15 |
Check [`DisplayFromStr`] for details. |
| 16 |
* Support for arrays larger than 32 elements or using const generics. |
| 17 |
With `serde_as` large arrays are supported, even if they are nested in other types. |
| 18 |
`[bool; 64]`, `Option<[u8; M]>`, and `Box<[[u8; 64]; N]>` are all supported, as [this examples shows](#large-and-const-generic-arrays). |
| 19 |
* Skip serializing all empty `Option` types with [`#[skip_serializing_none]`][skip_serializing_none]. |
| 20 |
* Apply a prefix / suffix to each field name of a struct, without changing the de/serialize implementations of the struct using [`with_prefix!`][] / [`with_suffix!`][]. |
| 21 |
* Deserialize a comma separated list like `#hash,#tags,#are,#great` into a `Vec<String>`. |
| 22 |
Check the documentation for [`serde_with::StringWithSeparator::<CommaSeparator, T>`][StringWithSeparator]. |
| 23 |
|
| 24 |
### Getting Help |
| 25 |
|
| 26 |
**Check out the [user guide][user guide] to find out more tips and tricks about this crate.** |
| 27 |
|
| 28 |
For further help using this crate, you can [open a new discussion](https://github.com/jonasbb/serde_with/discussions/new) or ask on [users.rust-lang.org](https://users.rust-lang.org/). |
| 29 |
For bugs, please open a [new issue](https://github.com/jonasbb/serde_with/issues/new) on GitHub. |
| 30 |
|
| 31 |
## Use `serde_with` in your Project |
| 32 |
|
| 33 |
```bash |
| 34 |
# Add the current version to your Cargo.toml |
| 35 |
cargo add serde_with |
| 36 |
``` |
| 37 |
|
| 38 |
The crate contains different features for integration with other common crates. |
| 39 |
Check the [feature flags][] section for information about all available features. |
| 40 |
|
| 41 |
## Examples |
| 42 |
|
| 43 |
Annotate your struct or enum to enable the custom de/serializer. |
| 44 |
The `#[serde_as]` attribute must be placed *before* the `#[derive]`. |
| 45 |
|
| 46 |
The `as` is analogous to the `with` attribute of serde. |
| 47 |
You mirror the type structure of the field you want to de/serialize. |
| 48 |
You can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`. |
| 49 |
The default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`. |
| 50 |
|
| 51 |
### `DisplayFromStr` |
| 52 |
|
| 53 |
[](https://www.rustexplorer.com/b/py7ida) |
| 54 |
```rust |
| 55 |
#[serde_as] |
| 56 |
#[derive(Deserialize, Serialize)] |
| 57 |
struct Foo { |
| 58 |
// Serialize with Display, deserialize with FromStr |
| 59 |
#[serde_as(as = "DisplayFromStr")] |
| 60 |
bar: u8, |
| 61 |
} |
| 62 |
|
| 63 |
// This will serialize |
| 64 |
Foo {bar: 12} |
| 65 |
|
| 66 |
// into this JSON |
| 67 |
{"bar": "12"} |
| 68 |
``` |
| 69 |
|
| 70 |
### Large and const-generic arrays |
| 71 |
|
| 72 |
serde does not support arrays with more than 32 elements or using const-generics. |
| 73 |
The `serde_as` attribute allows circumventing this restriction, even for nested types and nested arrays. |
| 74 |
|
| 75 |
On top of it, `[u8; N]` (aka, bytes) can use the specialized `"Bytes"` for efficiency much like the `serde_bytes` crate. |
| 76 |
|
| 77 |
[](https://www.rustexplorer.com/b/um0xyi) |
| 78 |
```rust |
| 79 |
#[serde_as] |
| 80 |
#[derive(Deserialize, Serialize)] |
| 81 |
struct Arrays<const N: usize, const M: usize> { |
| 82 |
#[serde_as(as = "[_; N]")] |
| 83 |
constgeneric: [bool; N], |
| 84 |
|
| 85 |
#[serde_as(as = "Box<[[_; 64]; N]>")] |
| 86 |
nested: Box<[[u8; 64]; N]>, |
| 87 |
|
| 88 |
#[serde_as(as = "Option<[_; M]>")] |
| 89 |
optional: Option<[u8; M]>, |
| 90 |
|
| 91 |
#[serde_as(as = "Bytes")] |
| 92 |
bytes: [u8; M], |
| 93 |
} |
| 94 |
|
| 95 |
// This allows us to serialize a struct like this |
| 96 |
let arrays: Arrays<100, 128> = Arrays { |
| 97 |
constgeneric: [true; 100], |
| 98 |
nested: Box::new([[111; 64]; 100]), |
| 99 |
optional: Some([222; 128]), |
| 100 |
bytes: [0x42; 128], |
| 101 |
}; |
| 102 |
assert!(serde_json::to_string(&arrays).is_ok()); |
| 103 |
``` |
| 104 |
|
| 105 |
### `skip_serializing_none` |
| 106 |
|
| 107 |
This situation often occurs with JSON, but other formats also support optional fields. |
| 108 |
If many fields are optional, putting the annotations on the structs can become tedious. |
| 109 |
The `#[skip_serializing_none]` attribute must be placed *before* the `#[derive]`. |
| 110 |
|
| 111 |
[](https://www.rustexplorer.com/b/xr1tm0) |
| 112 |
```rust |
| 113 |
#[skip_serializing_none] |
| 114 |
#[derive(Deserialize, Serialize)] |
| 115 |
struct Foo { |
| 116 |
a: Option<usize>, |
| 117 |
b: Option<usize>, |
| 118 |
c: Option<usize>, |
| 119 |
d: Option<usize>, |
| 120 |
e: Option<usize>, |
| 121 |
f: Option<usize>, |
| 122 |
g: Option<usize>, |
| 123 |
} |
| 124 |
|
| 125 |
// This will serialize |
| 126 |
Foo {a: None, b: None, c: None, d: Some(4), e: None, f: None, g: Some(7)} |
| 127 |
|
| 128 |
// into this JSON |
| 129 |
{"d": 4, "g": 7} |
| 130 |
``` |
| 131 |
|
| 132 |
### Advanced `serde_as` usage |
| 133 |
|
| 134 |
This example is mainly supposed to highlight the flexibility of the `serde_as` annotation compared to [serde's `with` annotation][with-annotation]. |
| 135 |
More details about `serde_as` can be found in the [user guide]. |
| 136 |
|
| 137 |
```rust |
| 138 |
use std::time::Duration; |
| 139 |
|
| 140 |
#[serde_as] |
| 141 |
#[derive(Deserialize, Serialize)] |
| 142 |
enum Foo { |
| 143 |
Durations( |
| 144 |
// Serialize them into a list of number as seconds |
| 145 |
#[serde_as(as = "Vec<DurationSeconds>")] |
| 146 |
Vec<Duration>, |
| 147 |
), |
| 148 |
Bytes { |
| 149 |
// We can treat a Vec like a map with duplicates. |
| 150 |
// JSON only allows string keys, so convert i32 to strings |
| 151 |
// The bytes will be hex encoded |
| 152 |
#[serde_as(as = "Map<DisplayFromStr, Hex>")] |
| 153 |
bytes: Vec<(i32, Vec<u8>)>, |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
// This will serialize |
| 158 |
Foo::Durations( |
| 159 |
vec![Duration::new(5, 0), Duration::new(3600, 0), Duration::new(0, 0)] |
| 160 |
) |
| 161 |
// into this JSON |
| 162 |
{ |
| 163 |
"Durations": [5, 3600, 0] |
| 164 |
} |
| 165 |
|
| 166 |
// and serializes |
| 167 |
Foo::Bytes { |
| 168 |
bytes: vec![ |
| 169 |
(1, vec![0, 1, 2]), |
| 170 |
(-100, vec![100, 200, 255]), |
| 171 |
(1, vec![0, 111, 222]), |
| 172 |
], |
| 173 |
} |
| 174 |
// into this JSON |
| 175 |
{ |
| 176 |
"Bytes": { |
| 177 |
"bytes": { |
| 178 |
"1": "000102", |
| 179 |
"-100": "64c8ff", |
| 180 |
"1": "006fde" |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
``` |
| 185 |
|
| 186 |
[`DisplayFromStr`]: https://docs.rs/serde_with/3.12.0/serde_with/struct.DisplayFromStr.html |
| 187 |
[`with_prefix!`]: https://docs.rs/serde_with/3.12.0/serde_with/macro.with_prefix.html |
| 188 |
[`with_suffix!`]: https://docs.rs/serde_with/3.12.0/serde_with/macro.with_suffix.html |
| 189 |
[feature flags]: https://docs.rs/serde_with/3.12.0/serde_with/guide/feature_flags/index.html |
| 190 |
[skip_serializing_none]: https://docs.rs/serde_with/3.12.0/serde_with/attr.skip_serializing_none.html |
| 191 |
[StringWithSeparator]: https://docs.rs/serde_with/3.12.0/serde_with/struct.StringWithSeparator.html |
| 192 |
[user guide]: https://docs.rs/serde_with/3.12.0/serde_with/guide/index.html |
| 193 |
[with-annotation]: https://serde.rs/field-attrs.html#with |
| 194 |
[as-annotation]: https://docs.rs/serde_with/3.12.0/serde_with/guide/serde_as/index.html |
| 195 |
|
| 196 |
## License |
| 197 |
|
| 198 |
Licensed under either of |
| 199 |
|
| 200 |
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) |
| 201 |
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) |
| 202 |
|
| 203 |
at your option. |
| 204 |
|
| 205 |
## Contribution |
| 206 |
|
| 207 |
For detailed contribution instructions please read [`CONTRIBUTING.md`]. |
| 208 |
|
| 209 |
Unless you explicitly state otherwise, any contribution intentionally submitted |
| 210 |
for inclusion in the work by you, as defined in the Apache-2.0 license, shall |
| 211 |
be dual-licensed as above, without any additional terms or conditions. |
| 212 |
|
| 213 |
[`CONTRIBUTING.md`]: https://github.com/jonasbb/serde_with/blob/master/CONTRIBUTING.md |