Hello there! I'm sorry if this has been already asked before but I just want to get confirmation if what I want to do is currently possible with serde
or not. For that I'll use an example similar to what I have now:
Basically I have an actix endpoint that receives a request with the following definition:
struct EndpointPayload {
#[serde(deserialize_with = "option_date_time_iso8601_deserializer")]
from_date: Option<chrono::NaiveDateTime>,
#[serde(deserialize_with = "option_date_time_iso8601_deserializer")]
to_date: Option<chrono::NaiveDateTime>,
}
pub fn option_date_time_iso8601_deserializer<'de, D>(deserializer: D) -> Result<Option<chrono::NaiveDateTime>, D::Error>
where
D: Deserializer<'de>,
{
match Option::deserialize(deserializer)? {
Some(x) => Ok(Some(
deserialize_string_to_naive_date_time(x).map_err(|_| D::Error::custom("Couldn't deserialize NaiveDateTime from string"))?,
)),
None => Ok(None),
}
}
fn deserialize_string_to_naive_date_time(s: &str) -> chrono::ParseResult<chrono::NaiveDateTime> {
let date_format = "%Y-%m-%dT%H:%M:%S%.3fZ";
chrono::NaiveDateTime::parse_from_str(s, &date_format)
}
Now, as you can see basically the endpoint receives a JSON body where the dates are strings in an ISO8601 format, now my problem is that sometimes the date may not be properly formatted, that makes my parsing code in deserialize_string_to_naive_date_time
which is fine, but I would like to get the name of the JSON field that provoked that error.
I've searched both the source of serde_json
and some topics around but I don't think it is something that can currently be done, at least not without changing serde_json
itself.
TLDR: Is there a way to get the name of the JSON fields in a custom deserialization function?