Module serde_with::rust::maps_first_key_wins [−][src]
Ensure that the first key is taken, if duplicate keys exist
By default serde has a last-key-wins implementation, if duplicate keys for a map exist. Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
The implementation supports both the HashMap
and the BTreeMap
from the standard library.
Example
#[derive(Deserialize)] struct Doc { #[serde(with = "::serde_with::rust::maps_first_key_wins")] map: HashMap<usize, usize>, } // Maps are serialized normally, let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#; let mut v = Doc { map: HashMap::new(), }; v.map.insert(1, 1); v.map.insert(2, 2); v.map.insert(3, 3); assert_eq!(v, serde_json::from_str(s).unwrap()); // but create an error if duplicate keys, like the `1`, exist. let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#; let mut v = Doc { map: HashMap::new(), }; v.map.insert(1, 1); v.map.insert(2, 2); assert_eq!(v, serde_json::from_str(s).unwrap());
Functions
deserialize | Deserialize a map and return an error on duplicate keys |