The KeyValueMap<T> helper allows you to serialize a sequence (like a Vec<T>) into a JSON/YAML map where each element of the sequence becomes a map entry.
To use this, you must define which part of your element serves as the map key:
- For Structs: Use the
#[serde(rename = "$key$")] attribute on the field you want to use as the key. The field named $key$ will be extracted as the map key, and all other fields will form the map value. - For Tuples, Tuple Structs, or Sequences: The first element is automatically used as the map key.
- For Maps: The map-key that is named
$key$ is used.
You apply this using the #[serde_as(as = "KeyValueMap<_>")] attribute on the field containing the sequence within a struct annotated with #[serde_as].
```rust
# #[cfg(feature = "macros")] {
# use serde::{Deserialize, Serialize};
# use serde_with::{serde_as, KeyValueMap};
#
# #[derive(Debug, Clone, PartialEq, Eq)]
# #[derive(Serialize, Deserialize)]
# struct SimpleStruct {
# b: bool,
# #[serde(rename = "$key$")]
# id: String,
# i: i32,
# }
#
# #[serde_as]
# # [derive(Debug, Clone, PartialEq, Eq)]
# #[derive(Serialize, Deserialize)]
# struct KVMap(#[serde_as(as = "KeyValueMap<_>")] Vec<SimpleStruct>);
#
# let values = KVMap(vec![
# SimpleStruct { b: false, id: "id-0000".to_string(), i: 123 },
# SimpleStruct { b: true, id: "id-0001".to_string(), i: 555 },
# ]);
#
# // Serializes to: {"id-0000": {"b": false, "i": 123}, "id-0001": {"b": true, "i": 555}}
# ```