Struct serde_with::Map

source ·
pub struct Map<K, V>(_);
Expand description

This serializes a list of tuples into a map

Normally, you want to use a HashMap or a BTreeMap when deserializing a map. However, sometimes this is not possible due to type constraints, e.g., if the type implements neither Hash nor Ord. Another use case is deserializing a map with duplicate keys.

The implementation is generic using the FromIterator and IntoIterator traits. Therefore, all of Vec, VecDeque, and LinkedList and anything which implements those are supported.

Examples

Wrapper does not implement Hash nor Ord, thus prohibiting the use HashMap or BTreeMap. The JSON also contains a duplicate key.

#[serde_as]
#[derive(Debug, Deserialize, Serialize, Default)]
struct S {
    #[serde_as(as = "Map<_, _>")]
    s: Vec<(Wrapper<i32>, String)>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(transparent)]
struct Wrapper<T>(T);

let data = S {
    s: vec![
        (Wrapper(1), "a".to_string()),
        (Wrapper(2), "b".to_string()),
        (Wrapper(3), "c".to_string()),
        (Wrapper(2), "d".to_string()),
    ],
};

let json = r#"{
  "s": {
    "1": "a",
    "2": "b",
    "3": "c",
    "2": "d"
  }
}"#;
assert_eq!(json, serde_json::to_string_pretty(&data).unwrap());

Trait Implementations§

Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Deserialize this value from the given Serde deserializer.
Serialize this value into the given Serde serializer.
Serialize this value into the given Serde serializer.
Serialize this value into the given Serde serializer.
Serialize this value into the given Serde serializer.
Serialize this value into the given Serde serializer.
Serialize this value into the given Serde serializer.
Serialize this value into the given Serde serializer.
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

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

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.