Using Serde on simple Struct that has external struct not Serializable

I have a very simple struct:

use internment::Intern;

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Name {
    pub(crate) name: Intern<String>,
}

I tried to derive Serialize and Deserialize from the serde crate but it is not implemented for Intern so it didn't work.

I managed to follow the docs and implement a customer Serializer:

impl Serialize for Name {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Name", 1)?;
        state.serialize_field("name", &self.name.deref())?;
        state.end()
    }
}

The docs readily state implementing a Deserializer is more complicated. I probably can muddle through and get it working but on the face of it there is a lot of bolier plate code. Am I doing the right, and necessary thing, for such a basic struct?

Note that internment::Intern does implement Serialize and Deserialize, if you enable the serde feature for internment in your Cargo.toml:

[dependencies]
internment = { version = "0.8", features = ["serde"] }
1 Like

Ah great, i checked the docs but didn't see the feature. In any case, its fixed now, but had it not implemented serde, was what I was suggesting necessary?

Rather than implementing Serialize and Deserialize by hand, you could've tried to use the derive macros for the remote type. I think in your case implementing by hand would've been easier though.

You could also use the #[serde(with = ...)] attribute to specify a module with free functions for serialization and deserialization of individual fields. Then you can continue using the derive macro.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.