I'm serializing a HashMap
with serde, like so:
#[derive(Serialize, Deserialize)]
struct MyStruct {
map: HashMap<String, String>
}
HashMap
's key order is unspecified, and since the hashing is randomized (see documentation), the keys actually end up coming out in different order between identical runs.
I'd like my HashMap
to be serialized in sorted (e.g. alphabetical) key order, so that the serialization is deterministic.
I could use a BTreeMap
instead of a HashMap
to achieve this, as BTreeMap::keys()
returns its keys in sorted order, but I'd rather not change my data structure just to accommodate the serialization logic.
How do I tell serde to sort the HashMap
keys before serializing?