Struct serde_with::OneOrMany[][src]

pub struct OneOrMany<T, FORMAT: Format = PreferOne>(_);
Expand description

Deserialize one or many elements

Sometime it is desireable to have a shortcut in writing 1-element lists in a config file. Usually, this is done by either writing a list or the list element itself. This distinction is not semantically important on the Rust side, thus both forms should serialize into the same Vec.

The OneOrMany adapter achieves exactly this use case. The serialization behavior can be tweaked to either always serialize as a list using PreferMany or to serialize as the inner element if possible using PreferOne. By default PreferOne is assumed, which can also be omitted like OneOrMany<_>.

Examples

#[serde_as]
#[derive(Deserialize, serde::Serialize)]
struct Data {
    #[serde_as(deserialize_as = "OneOrMany<_, PreferOne>")]
    countries: Vec<String>,
    #[serde_as(deserialize_as = "OneOrMany<_, PreferMany>")]
    cities: Vec<String>,
}

// The adapter allows deserializing a `Vec` from either
// a single element
let j = json!({
    "countries": "Spain",
    "cities": "Berlin",
});
assert!(serde_json::from_value::<Data>(j).is_ok());

// or from a list.
let j = json!({
    "countries": ["Germany", "France"],
    "cities": ["Amsterdam"],
});
assert!(serde_json::from_value::<Data>(j).is_ok());

// For serialization you can choose how a single element should be encoded.
// Either directly, with `PreferOne` (default), or as a list with `PreferMany`.
let data = Data {
    countries: vec!["Spain".to_string()],
    cities: vec!["Berlin".to_string()],
};
let j = json!({
    "countries": "Spain",
    "cities": ["Berlin"],
});
assert_eq!(data, serde_json::from_value(j).unwrap());

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Deserialize this value from the given Serde deserializer.

Serialize this value into the given Serde serializer.

Serialize this value into the given Serde serializer.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.