| 1 |
# `serde_as` Annotation |
| 2 |
|
| 3 |
This is an alternative to serde's `with` annotation. |
| 4 |
It is more flexible and composable, but works with fewer types. |
| 5 |
|
| 6 |
The scheme is based on two new traits, [`SerializeAs`] and [`DeserializeAs`], which need to be implemented by all types which want to be compatible with `serde_as`. |
| 7 |
The proc-macro attribute [`#[serde_as]`][crate::serde_as] exists as a usability boost for users. |
| 8 |
The basic design of `serde_as` was developed by [@markazmierczak](https://github.com/markazmierczak). |
| 9 |
|
| 10 |
This page contains some general advice on the usage of `serde_as` and on implementing the necessary traits. |
| 11 |
[**A list of all supported transformations enabled by `serde_as` is available on this page.**](crate::guide::serde_as_transformations) |
| 12 |
|
| 13 |
1. [Switching from serde's with to `serde_as`](#switching-from-serdes-with-to-serde_as) |
| 14 |
1. [Deserializing Optional Fields](#deserializing-optional-fields) |
| 15 |
2. [Gating `serde_as` on Features](#gating-serde_as-on-features) |
| 16 |
2. [Implementing `SerializeAs` / `DeserializeAs`](#implementing-serializeas--deserializeas) |
| 17 |
1. [Using `#[serde_as]` on types without `SerializeAs` and `Serialize` implementations](#using-serde_as-on-types-without-serializeas-and-serialize-implementations) |
| 18 |
2. [Using `#[serde_as]` with serde's remote derives](#using-serde_as-with-serdes-remote-derives) |
| 19 |
3. [Re-exporting `serde_as`](#re-exporting-serde_as) |
| 20 |
|
| 21 |
## Switching from serde's with to `serde_as` |
| 22 |
|
| 23 |
For the user, the main difference is that instead of |
| 24 |
|
| 25 |
```rust,ignore |
| 26 |
#[serde(with = "...")] |
| 27 |
``` |
| 28 |
|
| 29 |
you now have to write |
| 30 |
|
| 31 |
```rust,ignore |
| 32 |
#[serde_as(as = "...")] |
| 33 |
``` |
| 34 |
|
| 35 |
and place the `#[serde_as]` attribute *before* the `#[derive]` attribute. |
| 36 |
You still need the `#[derive(Serialize, Deserialize)]` on the struct/enum. |
| 37 |
You mirror the type structure of the field you want to de/serialize. |
| 38 |
You can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`. |
| 39 |
The default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`. |
| 40 |
|
| 41 |
Combined, this looks like: |
| 42 |
|
| 43 |
```rust |
| 44 |
use serde::{Deserialize, Serialize}; |
| 45 |
use serde_with::{serde_as, DisplayFromStr}; |
| 46 |
|
| 47 |
# #[allow(dead_code)] |
| 48 |
#[serde_as] |
| 49 |
#[derive(Serialize, Deserialize)] |
| 50 |
struct A { |
| 51 |
#[serde_as(as = "DisplayFromStr")] |
| 52 |
mime: mime::Mime, |
| 53 |
} |
| 54 |
``` |
| 55 |
|
| 56 |
The main advantage is that you can compose `serde_as` stuff, which is impossible with the `with` annotation. |
| 57 |
For example, the `mime` field from above could be nested in one or more data structures: |
| 58 |
|
| 59 |
```rust |
| 60 |
# use std::collections::BTreeMap; |
| 61 |
# use serde::{Deserialize, Serialize}; |
| 62 |
# use serde_with::{serde_as, DisplayFromStr}; |
| 63 |
# |
| 64 |
# #[allow(dead_code)] |
| 65 |
#[serde_as] |
| 66 |
#[derive(Serialize, Deserialize)] |
| 67 |
struct A { |
| 68 |
#[serde_as(as = "Option<BTreeMap<_, Vec<DisplayFromStr>>>")] |
| 69 |
mime: Option<BTreeMap<String, Vec<mime::Mime>>>, |
| 70 |
} |
| 71 |
``` |
| 72 |
|
| 73 |
### Deserializing Optional Fields |
| 74 |
|
| 75 |
In many cases, using `serde_as` on a field of type `Option` should behave as expected. |
| 76 |
This means the field can still be missing during deserialization and will be filled with the value `None`. |
| 77 |
|
| 78 |
This "magic" can break in some cases. Then it becomes necessary to apply `#[serde(default)]` on the field in question. |
| 79 |
If the field is of type `Option<T>` and the conversion type is of `Option<S>`, the default attribute is automatically applied. |
| 80 |
These variants are detected as `Option`. |
| 81 |
|
| 82 |
* `Option` |
| 83 |
* `std::option::Option`, with or without leading `::` |
| 84 |
* `core::option::Option`, with or without leading `::` |
| 85 |
|
| 86 |
Any renaming will interfere with the detection, such as `use std::option::Option as StdOption;`. |
| 87 |
For more information, you can inspect the documentation of the `serde_as` macro. |
| 88 |
|
| 89 |
```rust |
| 90 |
# use serde::{Deserialize, Serialize}; |
| 91 |
# use serde_with::{serde_as, DisplayFromStr}; |
| 92 |
# |
| 93 |
# #[allow(dead_code)] |
| 94 |
#[serde_as] |
| 95 |
#[derive(Serialize, Deserialize)] |
| 96 |
struct A { |
| 97 |
#[serde_as(as = "Option<DisplayFromStr>")] |
| 98 |
// In this situation both `Option`s will be correctly identified and |
| 99 |
// `#[serde(default)]` will be applied on this field. |
| 100 |
val: Option<u32>, |
| 101 |
} |
| 102 |
``` |
| 103 |
|
| 104 |
In the future, this behavior might change and `default` would be applied on `Option<T>` fields. |
| 105 |
You can add your feedback at [serde_with#185]. |
| 106 |
|
| 107 |
### Gating `serde_as` on Features |
| 108 |
|
| 109 |
Gating `serde_as` behind optional features is possible using the `cfg_eval` attribute. |
| 110 |
The attribute is available via the [`cfg_eval`-crate](https://docs.rs/cfg_eval) on stable or using the [Rust attribute](https://doc.rust-lang.org/1.70.0/core/prelude/v1/attr.cfg_eval.html) on unstable nightly. |
| 111 |
|
| 112 |
The `cfg_eval` attribute must be placed **before** the struct-level `serde_as` attribute. |
| 113 |
You can combine them in a single `cfg_attr`, as long as the order is preserved. |
| 114 |
|
| 115 |
```rust,ignore |
| 116 |
#[cfg_attr(feature="serde", cfg_eval::cfg_eval, serde_as)] |
| 117 |
#[cfg_attr(feature="serde", derive(Serialize, Deserialize))] |
| 118 |
struct Struct { |
| 119 |
#[cfg_attr(feature="serde", serde_as(as = "Vec<(_, _)>"))] |
| 120 |
map: HashMap<(i32,i32), i32>, |
| 121 |
} |
| 122 |
``` |
| 123 |
|
| 124 |
## Implementing `SerializeAs` / `DeserializeAs` |
| 125 |
|
| 126 |
You can support [`SerializeAs`] / [`DeserializeAs`] on your own types too. |
| 127 |
Most "leaf" types do not need to implement these traits, since they are supported implicitly. |
| 128 |
"Leaf" types refer to types which directly serialize, like plain data types. |
| 129 |
[`SerializeAs`] / [`DeserializeAs`] is essential for collection types, like `Vec` or `BTreeMap`, since they need special handling for the key/value de/serialization such that the conversions can be done on the key/values. |
| 130 |
You also find them implemented on the conversion types, such as the [`DisplayFromStr`] type. |
| 131 |
These comprise the bulk of this crate and allow you to perform all the nice conversions to [hex strings], the [bytes to string converter], or [duration to UNIX epoch]. |
| 132 |
|
| 133 |
In many cases, conversion is only required from one serializable type to another one, without requiring the full power of the `Serialize` or `Deserialize` traits. |
| 134 |
In these cases, the [`serde_conv!`] macro conveniently allows defining conversion types without the boilerplate. |
| 135 |
The documentation of [`serde_conv!`] contains more details how to use it. |
| 136 |
|
| 137 |
The trait documentations for [`SerializeAs`] and [`DeserializeAs`] describe in details how to implement them for container types like `Box` or `Vec` and other types. |
| 138 |
|
| 139 |
### Using `#[serde_as]` on types without `SerializeAs` and `Serialize` implementations |
| 140 |
|
| 141 |
The `SerializeAs` and `DeserializeAs` traits can easily be used together with types from other crates without running into orphan rule problems. |
| 142 |
This is a distinct advantage of the `serde_as` system. |
| 143 |
For this example, we assume we have a type `RemoteType` from a dependency which does not implement `Serialize` nor `SerializeAs`. |
| 144 |
We assume we have a module containing a `serialize` and a `deserialize` function, which can be used in the `#[serde(with = "MODULE")]` annotation. |
| 145 |
You find an example in the [official serde documentation](https://serde.rs/custom-date-format.html). |
| 146 |
|
| 147 |
Our goal is to serialize this `Data` struct. |
| 148 |
Currently, we do not have anything we can use to replace `???` with, since `_` only works if `RemoteType` would implement `Serialize`, which it does not. |
| 149 |
|
| 150 |
```rust |
| 151 |
# #[cfg(any())] { |
| 152 |
#[serde_as] |
| 153 |
#[derive(serde::Serialize)] |
| 154 |
struct Data { |
| 155 |
#[serde_as(as = "Vec<???>")] |
| 156 |
vec: Vec<RemoteType>, |
| 157 |
} |
| 158 |
# } |
| 159 |
``` |
| 160 |
|
| 161 |
We need to create a new type for which we can implement `SerializeAs`, to replace the `???`. |
| 162 |
The `SerializeAs` implementation is **always** written for a local type. |
| 163 |
This allows it to seamlessly work with types from dependencies without running into orphan rule problems. |
| 164 |
|
| 165 |
```rust |
| 166 |
# #[cfg(any())] { |
| 167 |
struct LocalType; |
| 168 |
|
| 169 |
impl SerializeAs<RemoteType> for LocalType { |
| 170 |
fn serialize_as<S>(value: &RemoteType, serializer: S) -> Result<S::Ok, S::Error> |
| 171 |
where |
| 172 |
S: Serializer, |
| 173 |
{ |
| 174 |
MODULE::serialize(value, serializer) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
impl<'de> DeserializeAs<'de, RemoteType> for LocalType { |
| 179 |
fn deserialize_as<D>(deserializer: D) -> Result<RemoteType, D::Error> |
| 180 |
where |
| 181 |
D: Deserializer<'de>, |
| 182 |
{ |
| 183 |
MODULE::deserialize(deserializer) |
| 184 |
} |
| 185 |
} |
| 186 |
# } |
| 187 |
``` |
| 188 |
|
| 189 |
This is what the final implementation looks like. |
| 190 |
We assumed we already have a module `MODULE` with a `serialize` function, which we use here to provide the implementation. |
| 191 |
As can be seen, this is mostly boilerplate, since the most part is encapsulated in `$module::serialize`. |
| 192 |
The final `Data` struct will now look like: |
| 193 |
|
| 194 |
```rust |
| 195 |
# #[cfg(any())] { |
| 196 |
#[serde_as] |
| 197 |
#[derive(serde::Serialize)] |
| 198 |
struct Data { |
| 199 |
#[serde_as(as = "Vec<LocalType>")] |
| 200 |
vec: Vec<RemoteType>, |
| 201 |
} |
| 202 |
# } |
| 203 |
``` |
| 204 |
|
| 205 |
### Using `#[serde_as]` with serde's remote derives |
| 206 |
|
| 207 |
A special case of the above section is using it on remote derives. |
| 208 |
This is a special functionality of serde, where it derives the de/serialization code for a type from another crate if all fields are `pub`. |
| 209 |
You can find all the details in the [official serde documentation](https://serde.rs/remote-derive.html). |
| 210 |
|
| 211 |
```rust |
| 212 |
# #[cfg(any())] { |
| 213 |
// Pretend that this is somebody else's crate, not a module. |
| 214 |
mod other_crate { |
| 215 |
// Neither Serde nor the other crate provides Serialize and Deserialize |
| 216 |
// impls for this struct. |
| 217 |
pub struct Duration { |
| 218 |
pub secs: i64, |
| 219 |
pub nanos: i32, |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
//////////////////////////////////////////////////////////////////////////////// |
| 224 |
|
| 225 |
use other_crate::Duration; |
| 226 |
|
| 227 |
// Serde calls this the definition of the remote type. It is just a copy of the |
| 228 |
// remote data structure. The `remote` attribute gives the path to the actual |
| 229 |
// type we intend to derive code for. |
| 230 |
#[derive(serde::Serialize, serde::Deserialize)] |
| 231 |
#[serde(remote = "Duration")] |
| 232 |
struct DurationDef { |
| 233 |
secs: i64, |
| 234 |
nanos: i32, |
| 235 |
} |
| 236 |
# } |
| 237 |
``` |
| 238 |
|
| 239 |
Our goal is now to use `Duration` within `serde_as`. |
| 240 |
We use the existing `DurationDef` type and its `serialize` and `deserialize` functions. |
| 241 |
We can write this implementation. |
| 242 |
The implementation for `DeserializeAs` works analogue. |
| 243 |
|
| 244 |
```rust |
| 245 |
# #[cfg(any())] { |
| 246 |
impl SerializeAs<Duration> for DurationDef { |
| 247 |
fn serialize_as<S>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> |
| 248 |
where |
| 249 |
S: serde::Serializer, |
| 250 |
{ |
| 251 |
DurationDef::serialize(value, serializer) |
| 252 |
} |
| 253 |
} |
| 254 |
# } |
| 255 |
``` |
| 256 |
|
| 257 |
This now allows us to use `Duration` for serialization. |
| 258 |
|
| 259 |
```rust |
| 260 |
# #[cfg(any())] { |
| 261 |
use other_crate::Duration; |
| 262 |
|
| 263 |
#[serde_as] |
| 264 |
#[derive(serde::Serialize)] |
| 265 |
struct Data { |
| 266 |
#[serde_as(as = "Vec<DurationDef>")] |
| 267 |
vec: Vec<Duration>, |
| 268 |
} |
| 269 |
# } |
| 270 |
``` |
| 271 |
|
| 272 |
## Re-exporting `serde_as` |
| 273 |
|
| 274 |
If `serde_as` is being used in a context where the `serde_with` crate is not available from the root |
| 275 |
path, but is re-exported at some other path, the `crate = "..."` attribute argument should be used |
| 276 |
to specify its path. This may be the case if `serde_as` is being used in a procedural macro - |
| 277 |
otherwise, users of that macro would need to add `serde_with` to their own Cargo manifest. |
| 278 |
|
| 279 |
The `crate` argument will generally be used in conjunction with [`serde`'s own `crate` argument]. |
| 280 |
|
| 281 |
For example, a type definition may be defined in a procedural macro: |
| 282 |
|
| 283 |
```rust,ignore |
| 284 |
// some_other_lib_derive/src/lib.rs |
| 285 |
|
| 286 |
use proc_macro::TokenStream; |
| 287 |
use quote::quote; |
| 288 |
|
| 289 |
#[proc_macro] |
| 290 |
pub fn define_some_type(_item: TokenStream) -> TokenStream { |
| 291 |
let def = quote! { |
| 292 |
#[serde(crate = "::some_other_lib::serde")] |
| 293 |
#[::some_other_lib::serde_with::serde_as(crate = "::some_other_lib::serde_with")] |
| 294 |
#[derive(::some_other_lib::serde::Deserialize)] |
| 295 |
struct Data { |
| 296 |
#[serde_as(as = "_")] |
| 297 |
a: u32, |
| 298 |
} |
| 299 |
}; |
| 300 |
|
| 301 |
TokenStream::from(def) |
| 302 |
} |
| 303 |
``` |
| 304 |
|
| 305 |
This can be re-exported through a library which also re-exports `serde` and `serde_with`: |
| 306 |
|
| 307 |
```rust,ignore |
| 308 |
// some_other_lib/src/lib.rs |
| 309 |
|
| 310 |
pub use serde; |
| 311 |
pub use serde_with; |
| 312 |
pub use some_other_lib_derive::define_some_type; |
| 313 |
``` |
| 314 |
|
| 315 |
The procedural macro can be used by other crates without any additional imports: |
| 316 |
|
| 317 |
```rust,ignore |
| 318 |
// consuming_crate/src/main.rs |
| 319 |
|
| 320 |
some_other_lib::define_some_type!(); |
| 321 |
``` |
| 322 |
|
| 323 |
[`DeserializeAs`]: crate::DeserializeAs |
| 324 |
[`DisplayFromStr`]: crate::DisplayFromStr |
| 325 |
[`serde_as`]: crate::serde_as |
| 326 |
[`serde_conv!`]: crate::serde_conv! |
| 327 |
[`serde`'s own `crate` argument]: https://serde.rs/container-attrs.html#crate |
| 328 |
[`SerializeAs`]: crate::SerializeAs |
| 329 |
[bytes to string converter]: crate::BytesOrString |
| 330 |
[duration to UNIX epoch]: crate::DurationSeconds |
| 331 |
[hex strings]: crate::hex::Hex |
| 332 |
[serde_with#185]: https://github.com/jonasbb/serde_with/issues/185 |