Crate serde_with[][src]

Expand description

docs.rs badge crates.io badge Build Status codecov


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:

Getting Help

Check out the user guide to find out more tips and tricks about this crate.

For further help using this crate you can open a new discussion or ask on users.rust-lang.org. For bugs please open a new issue on Github.

Use serde_with in your Project

Add this to your Cargo.toml:

[dependencies.serde_with]
version = "1.9.4"
features = [ "..." ]

The crate contains different features for integration with other common crates. Check the feature flags section for information about all available features.

Examples

Annotate your struct or enum to enable the custom de/serializer.

DisplayFromStr

#[serde_as]
#[derive(Deserialize, Serialize)]
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.

#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
struct Foo {
    a: Option<usize>,
    b: Option<usize>,
    c: Option<usize>,
    d: Option<usize>,
    e: Option<usize>,
    f: Option<usize>,
    g: Option<usize>,
}

// 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}

Advanced serde_as usage

This 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.

#[serde_as]
#[derive(Deserialize, Serialize)]
struct Foo {
     // Serialize them into a list of number as seconds
     #[serde_as(as = "Vec<DurationSeconds>")]
     durations: Vec<Duration>,
     // We can treat a Vec like a map with duplicates.
     // JSON only allows string keys, so convert i32 to strings
     // The bytes will be hex encoded
     #[serde_as(as = "BTreeMap<DisplayFromStr, Hex>")]
     bytes: Vec<(i32, Vec<u8>)>,
}

// 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"
    }
}

Modules

chrono

De/Serialization of chrono types

de

Module for DeserializeAs implementations

formats

Specify the format and how lenient the deserialization is

guide

serde_with User Guide

hex

De/Serialization of hexadecimal encoded bytes

json

De/Serialization of JSON

rust

De/Serialization for Rust’s builtin and std types

ser

Module for SerializeAs implementations

Macros

flattened_maybe

Support deserializing from flattened and non-flattened representation

serde_conv

Create new conversion adapters from functions

with_prefix

Serialize with an added prefix on every field name and deserialize by trimming away the prefix.

Structs

As

Adapter to convert from serde_as to the serde traits.

Bytes

Optimized handling of owned and borrowed byte representations.

BytesOrString

Deserialize from bytes or string

CommaSeparator

Predefined separator using a single comma

DefaultOnError

Deserialize value and return Default on error

DefaultOnNull

Deserialize Default from null values

DisplayFromStr

De/Serialize using Display and FromStr implementation

DurationMicroSeconds

Equivalent to DurationSeconds with micro-seconds as base unit.

DurationMicroSecondsWithFrac

Equivalent to DurationSecondsWithFrac with micro-seconds as base unit.

DurationMilliSeconds

Equivalent to DurationSeconds with milli-seconds as base unit.

DurationMilliSecondsWithFrac

Equivalent to DurationSecondsWithFrac with milli-seconds as base unit.

DurationNanoSeconds

Equivalent to DurationSeconds with nano-seconds as base unit.

DurationNanoSecondsWithFrac

Equivalent to DurationSecondsWithFrac with nano-seconds as base unit.

DurationSeconds

De/Serialize Durations as number of seconds.

DurationSecondsWithFrac

De/Serialize Durations as number of seconds.

FromInto

Serialize value by converting to/from a proxy type with serde support.

NoneAsEmptyString

De/Serialize a Option<String> type while transforming the empty string to None

OneOrMany

Deserialize one or many elements

PickFirst

Try multiple deserialization options until one succeeds.

Same

Adapter to convert from serde_as to the serde traits.

SpaceSeparator

Predefined separator using a single space

StringWithSeparator

De/Serialize a delimited collection using Display and FromStr implementation

TimestampMicroSeconds

Equivalent to TimestampSeconds with micro-seconds as base unit.

TimestampMicroSecondsWithFrac

Equivalent to TimestampSecondsWithFrac with micro-seconds as base unit.

TimestampMilliSeconds

Equivalent to TimestampSeconds with milli-seconds as base unit.

TimestampMilliSecondsWithFrac

Equivalent to TimestampSecondsWithFrac with milli-seconds as base unit.

TimestampNanoSeconds

Equivalent to TimestampSeconds with nano-seconds as base unit.

TimestampNanoSecondsWithFrac

Equivalent to TimestampSecondsWithFrac with nano-seconds as base unit.

TimestampSeconds

De/Serialize timestamps as seconds since the UNIX epoch

TimestampSecondsWithFrac

De/Serialize timestamps as seconds since the UNIX epoch

TryFromInto

Serialize value by converting to/from a proxy type with serde support.

Traits

DeserializeAs

A data structure that can be deserialized from any data format supported by Serde, analogue to Deserialize.

Separator

Separator for string-based collection de/serialization

SerializeAs

A data structure that can be serialized into any data format supported by Serde, analogue to Serialize.

Attribute Macros

serde_as

Convenience macro to use the serde_as system.

skip_serializing_none

Add skip_serializing_if annotations to Option fields.

Derive Macros

DeserializeFromStr

Deserialize value by using it’s FromStr implementation

SerializeDisplay

Serialize value by using it’s Display implementation