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
(De)serialize remote struct with Option<T> fields #1301
Labels
Comments
We do not currently support a way to use #[derive(Serialize, Deserialize)]
struct MyStruct {
#[serde(default, with = "opt_external_struct")]
value: Option<ExternalStruct>,
}
mod opt_external_struct {
use super::{ExternalStruct, ExternalStructDef};
use serde::{Serialize, Serializer, Deserialize, Deserializer};
pub fn serialize<S>(value: &Option<ExternalStruct>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
#[derive(Serialize)]
struct Helper<'a>(#[serde(with = "ExternalStructDef")] &'a ExternalStruct);
value.as_ref().map(Helper).serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<ExternalStruct>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Helper(#[serde(with = "ExternalStructDef")] ExternalStruct);
let helper = Option::deserialize(deserializer)?;
Ok(helper.map(|Helper(external)| external))
}
} |
Awesome, thanks a lot :) |
1ntEgr8
added a commit
to 1ntEgr8/prestino
that referenced
this issue
Jul 8, 2022
Lifted solution out of serde-rs/serde#1301
Has this feature been added recently? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey there,
I am trying to serialize and deserialize an
Option<T>
field of a struct I've implemented, whereT
is a struct implemented in an external crate. Following your documentation, I have implemented a Def struct using theremote
macro like so:Right now, my struct implementation looks as follows:
While this works as expected, wrapping
ExternalStruct
into anOption
and using theserde(default)
macro throws an error sayingexpected &external_crate::ExternalStruct.
:Do I have to implement a custom
serialize
anddeserialize
method to achieve this?Best,
Deniz
The text was updated successfully, but these errors were encountered: