pub struct KeyValueMap<T>(/* private fields */);
Expand description
Convert Vec
elements into key-value map entries
This maps a single struct/tuple/etc. to a map entry. The map key is converted to a struct field. The other values will be mapped to the map value.
The conversion supports structs, tuple structs, tuples, maps, and sequences.
Structs need a field that is named $key$
to be used as the map key.
This can be done with the #[serde(rename = "$key$")]
attribute.
Maps similarly need a map-key that is named $key$
.
For tuples, tuple structs, and sequences the first element is used as the map key.
§Examples
§Struct with String key in JSON
use serde_with::{serde_as, KeyValueMap};
#[derive(Serialize, Deserialize)]
struct SimpleStruct {
b: bool,
// The field named `$key$` will become the map key
#[serde(rename = "$key$")]
id: String,
i: i32,
}
#[serde_as]
#[derive(Serialize, Deserialize)]
struct KVMap(
#[serde_as(as = "KeyValueMap<_>")]
Vec<SimpleStruct>,
);
// ---
// This will serialize this list of values
let values = KVMap(vec![
SimpleStruct {
b: false,
id: "id-0000".to_string(),
i: 123,
},
SimpleStruct {
b: true,
id: "id-0001".to_string(),
i: 555,
},
SimpleStruct {
b: false,
id: "id-0002".to_string(),
i: 987,
},
]);
// into this JSON map
let expected =
r#"{
"id-0000": {
"b": false,
"i": 123
},
"id-0001": {
"b": true,
"i": 555
},
"id-0002": {
"b": false,
"i": 987
}
}"#;
// Both serialization and deserialization work flawlessly.
let serialized = serde_json::to_string_pretty(&values).unwrap();
assert_eq!(expected, serialized);
let deserialized: KVMap = serde_json::from_str(&serialized).unwrap();
assert_eq!(values, deserialized);
§Tuple struct with complex key in YAML
use serde_with::{serde_as, KeyValueMap};
use std::net::IpAddr;
#[derive(Serialize, Deserialize)]
struct TupleStruct (
// The first element in a tuple struct, tuple, or sequence becomes the map key
(IpAddr, u8),
bool,
);
#[serde_as]
#[derive(Serialize, Deserialize)]
struct KVMap(
#[serde_as(as = "KeyValueMap<_>")]
Vec<TupleStruct>,
);
// ---
// This will serialize this list of values
let values = KVMap(vec![
TupleStruct(
(IpAddr::from_str("127.0.0.1").unwrap(), 8),
true
),
TupleStruct(
(IpAddr::from_str("::1").unwrap(), 128),
true
),
TupleStruct(
(IpAddr::from_str("198.51.100.0").unwrap(), 24),
true
),
]);
// into this YAML
let expected =
r#"? - 127.0.0.1
- 8
: - true
? - ::1
- 128
: - true
? - 198.51.100.0
- 24
: - true
"#;
// Both serialization and deserialization work flawlessly.
let serialized = serde_yaml::to_string(&values).unwrap();
assert_eq!(expected, serialized);
let deserialized: KVMap = serde_yaml::from_str(&serialized).unwrap();
assert_eq!(values, deserialized);
Trait Implementations§
Source§impl<'de, T, TAs> DeserializeAs<'de, Vec<T>> for KeyValueMap<TAs>where
TAs: DeserializeAs<'de, T>,
impl<'de, T, TAs> DeserializeAs<'de, Vec<T>> for KeyValueMap<TAs>where
TAs: DeserializeAs<'de, T>,
Source§fn deserialize_as<D>(
deserializer: D,
) -> Result<Vec<T>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize_as<D>(
deserializer: D,
) -> Result<Vec<T>, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer.
Source§impl<T, TAs> SerializeAs<Vec<T>> for KeyValueMap<TAs>where
TAs: SerializeAs<T>,
impl<T, TAs> SerializeAs<Vec<T>> for KeyValueMap<TAs>where
TAs: SerializeAs<T>,
Source§fn serialize_as<S>(
source: &Vec<T>,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize_as<S>(
source: &Vec<T>,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
Serialize this value into the given Serde serializer.
Auto Trait Implementations§
impl<T> Freeze for KeyValueMap<T>
impl<T> RefUnwindSafe for KeyValueMap<T>where
T: RefUnwindSafe,
impl<T> Send for KeyValueMap<T>where
T: Send,
impl<T> Sync for KeyValueMap<T>where
T: Sync,
impl<T> Unpin for KeyValueMap<T>where
T: Unpin,
impl<T> UnwindSafe for KeyValueMap<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<S> AssignWithType for S
impl<S> AssignWithType for S
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<C, E> EntryToVal<C> for Ewhere
C: Collection<Entry = E>,
impl<C, E> EntryToVal<C> for Ewhere
C: Collection<Entry = E>,
Source§type Val = <C as Collection>::Val
type Val = <C as Collection>::Val
The type of values stored in the collection. This might be distinct from
Entry
in complex collections.
For example, in a HashMap
, while Entry
might be a ( key, value ) tuple, Val
might only be the value part.Source§fn entry_to_val(self) -> <E as EntryToVal<C>>::Val
fn entry_to_val(self) -> <E as EntryToVal<C>>::Val
Converts an entry into a value representation specific to the type of collection. This conversion is crucial
for handling operations on entries, especially when they need to be treated or accessed as individual values,
such as retrieving the value part from a key-value pair in a hash map.
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
Converts
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
Converts
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<Initial, Error, Final> TransitiveTryFrom<Error, Initial> for Final
impl<Initial, Error, Final> TransitiveTryFrom<Error, Initial> for Final
Source§impl<Error, Final, Initial> TransitiveTryInto<Error, Final> for Initial
impl<Error, Final, Initial> TransitiveTryInto<Error, Final> for Initial
Source§impl<C, Val> ValToEntry<C> for Valwhere
C: CollectionValToEntry<Val>,
impl<C, Val> ValToEntry<C> for Valwhere
C: CollectionValToEntry<Val>,
Source§fn val_to_entry(self) -> <C as CollectionValToEntry<Val>>::Entry
fn val_to_entry(self) -> <C as CollectionValToEntry<Val>>::Entry
Invokes the val_to_entry
function of the CollectionValToEntry
trait to convert the value to an entry.
Source§type Entry = <C as CollectionValToEntry<Val>>::Entry
type Entry = <C as CollectionValToEntry<Val>>::Entry
Represents the type of entry that corresponds to the value within the collection.