This crate provides custom de/serialization helpers to use in combination with serde's with-annotation and with the improved serde_as
-annotation.
Some common use cases are:
Display
and FromStr
traits, e.g., for u8
, url::Url
, or mime::Mime
.
Check [DisplayFromStr
][] or serde_with::rust::display_fromstr
for details.Option
types with #[skip_serializing_none]
.with_prefix!
][].#hash,#tags,#are,#great
into a Vec<String>
.
Check the documentation for serde_with::rust::StringWithSeparator::<CommaSeparator>
.Check out the user guide to find out more tips and tricks about this crate.
serde_with
in your ProjectAdd this to your Cargo.toml
:
toml
[dependencies.serde_with]
version = "1.5.0"
features = [ "..." ]
The crate contains different features for integration with other common crates. Check the feature flags section for information about all available features.
Annotate your struct or enum to enable the custom de/serializer.
DisplayFromStr
```rust
struct Foo { // Serialize with Display, deserialize with FromStr #[serde_as(as = "DisplayFromStr")] bar: u8, }
// This will serialize Foo {bar: 12}
// into this JSON {"bar": "12"} ```
skip_serializing_none
This situation often occurs with JSON, but other formats also support optional fields. If many fields are optional, putting the annotations on the structs can become tedious.
```rust
struct Foo {
a: Option
// This will serialize Foo {a: None, b: None, c: None, d: Some(4), e: None, f: None, g: Some(7)}
// into this JSON {"d": 4, "g": 7} ```
serde_as
usageThis example is mainly supposed to highlight the flexibility of the serde_as
-annotation compared to serde's with-annotation.
More details about serde_as
can be found in the user guide.
```rust
struct Foo {
// Serialize them into a list of number as seconds
#[serdeas(as = "Vec
// This will serialize Foo { durations: vec![Duration::new(5, 0), Duration::new(3600, 0), Duration::new(0, 0)], bytes: vec![ (1, vec![0, 1, 2]), (-100, vec![100, 200, 255]), (1, vec![0, 111, 222]), ], }
// into this JSON { "durations": [5, 3600, 0], "bytes": { "1": "000102", "-100": "64c8ff", "1": "006fde" } } ```
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.