I am looking to deserialize a nested JSON to a http crate HeaderMap structure with https://serde.rs/field-attrs.html#deserialize_with. How would I handle cases where the values are not strings but nested while still having access to a mutable variable to insert my items (see below)? Alternatively, is there a way to skip non-string entries.
{
"method": "GET",
"headers": {
"host": "test.whatever.app",
"x-some-key": [
"0.0.0.0",
"0.0.0.1"
]
}
fn deserialize_headers<'de, D>(deserializer: D) -> Result<HeaderMap<HeaderValue>, D::Error>
where
D: Deserializer<'de>,
{
struct HeaderVisitor;
impl<'de> Visitor<'de> for HeaderVisitor {
type Value = HeaderMap<HeaderValue>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a HeaderMap<HeaderValue>")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut headers = http::HeaderMap::new();
// How to handle the case where the header is not a string but a sequence?
while let Some((key, value)) = map.next_entry::<Cow<'_, str>, Cow<'_, str>>()? {
let header_name = key
.parse::<http::header::HeaderName>()
.map_err(A::Error::custom)?;
let header_value = HeaderValue::from_str(&value).map_err(A::Error::custom)?;
headers.append(header_name, header_value);
}
Ok(headers)
}
}
deserializer.deserialize_map(HeaderVisitor)
}