I am using a type (let's say Foo) that already implements Deserialize in its own crate, but it's not the one I want.
I can easily use #[serde(deserliaze_with = "custom_de"] on fields:
struct Bar {
#[serde(deserliaze_with = "deserialize_hashmap_foo_value"]
map: HashMap<String, Foo>
}
pub fn deserialize_hashmap_foo_value<'de, D, T>(d: D) -> Result<HashMap<T, Foo>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + std::hash::Hash + std::cmp::Eq,
{
let map: HashMap<T, String> = Deserialize::deserialize(d)?;
Ok(map
.into_iter()
.map(|(k, v)| (k, Foo::my_custom_deser(&v).unwrap()))
.collect())
}
And I am wondering whether I could re-use that function when I need to deserialize a struct myself, something like:
let response = &reqwest::get(url).bytes().await?
let result: HashMap<String, Foo> = serde_json::form_slice_with_deser(response, deserialize_hashmap_value_foo);
I've tried to define a newtype U256ValuedHashMap<T> and implementing from, into on it, but that creates quite a bit of mental over-head, and doesn't scale. Maybe a macro to define that type inline could work, idk...
Bonus
I'm also surprised how I can't just feed serde a custom deserialier for a type but I need to specify a custom deserializer for any wrapper value I want (HashMap, BTree, HashSet, Vec,...), that's seems like a very broad use case, am I missing some API?