👎 Deprecated since 1.8.0:

Use the more general map_as_tuple_list module.

Expand description

DEPRECATED De/Serialize a BTreeMap into a list of tuples

Use the map_as_tuple_list module which is more general than this. It should work with everything convertible to and from an Iterator including BTreeMap and HashMap.


Some formats, like JSON, have limitations on the type of keys for maps. In case of JSON, keys are restricted to strings. Rust features more powerful keys, for example tuple, which can not be serialized to JSON.

This helper serializes the BTreeMap into a list of tuples, which does not have the same type restrictions.

If you need to de/serialize a HashMap then use hashmap_as_tuple_list.

Converting to serde_as

The same functionality can be more clearly expressed using the serde_as macro. The _ is a placeholder which works for any type which implements Serialize/Deserialize, such as the tuple and u32 type.

#[serde_as]
#[derive(Deserialize, Serialize)]
struct A {
    #[serde_as(as = "Vec<(_, _)>")]
    s: BTreeMap<(String, u32), u32>,
}

Examples

#[derive(Deserialize, Serialize)]
struct A {
    #[serde(with = "serde_with::rust::btreemap_as_tuple_list")]
    s: BTreeMap<(String, u32), u32>,
}

let v: A = serde_json::from_value(json!({
    "s": [
        [["Hello", 123], 0],
        [["World", 456], 1]
    ]
})).unwrap();

assert_eq!(2, v.s.len());
assert_eq!(1, v.s[&("World".to_string(), 456)]);

Functions

Deserialize a map from a list of tuples

Serialize the map as a list of tuples