-
Notifications
You must be signed in to change notification settings - Fork 140
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can't serialize/deserialize struct which contains Option<chrono::DateTime<Utc>> field. #303
Comments
Unfortunately, using #[derive(Deserialize, Serialize, Debug)]
struct Dd {
#[serde(with = "opt_chrono_datetime_as_bson_datetime")]
#[serde(default)]
date: Option<chrono::DateTime<Utc>>,
}
mod opt_chrono_datetime_as_bson_datetime {
use chrono::Utc;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use mongodb::bson;
#[derive(Serialize, Deserialize)]
struct Helper(
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
chrono::DateTime<Utc>,
);
pub fn serialize<S>(
value: &Option<chrono::DateTime<Utc>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
value.map(Helper).serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<chrono::DateTime<Utc>>, D::Error>
where
D: Deserializer<'de>,
{
let helper: Option<Helper> = Option::deserialize(deserializer)?;
Ok(helper.map(|Helper(external)| external))
}
} Now there does exist the #[serde_as]
#[derive(Debug, Serialize, Deserialize)]
struct MyData {
#[serde_as(as = "Option<bson::DateTime>")]
date: Option<chrono::DateTime<Utc>>
} |
What if you try to import DateTime from MongoDB instead of chrono? |
Yep, using a BTW, the |
@patrickfreed even though I've tried your second option: #[serde_as]
#[derive(Debug, Serialize, Deserialize)]
struct MyData {
#[serde_as(as = "Option<bson::DateTime>")]
date: Option<chrono::DateTime<Utc>>
} Maybe I'm doing something obviously wrong that I'm not seeing? |
@ericpko You need to use the same major version of |
@jonasbb This worked! Thank you! |
Take the following struct as example:
When I try to complile, I get the following error message:
I think this should work for
start_date
andend_date
field just likecolls
field in the givenAuthorization
struct, sorry for that I go through documentation and can't find out an answer, am I miss something?The text was updated successfully, but these errors were encountered: