如何在 Serde 中序列化或反序列化 Arc<T>?

How do I serialize or deserialize an Arc<T> in Serde?

我有一个包含 children 自身类型的结构。这些 children 包含在 Arc 中,我在调用 serde_json::to_string 时遇到问题。我的结构是:

#[derive(Serialize, Deserialize)]
pub struct Category {
    pub id: i32,
    pub name: String,
    pub parent_id: i32,
    pub children: Vec<Arc<Category>>,
}

这会产生错误 the trait 'serde::Serialize' is not implemented for 'std::sync::Arc<db::queries::categories::Category>' 我已经尝试了几种不同的方法来使序列化工作,例如:

#[serde(serialize_with = "arc_category_vec")]
pub children: Vec<Arc<Category>>
fn arc_category_vec<S>(value: &Vec<Arc<Category>>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut seq = serializer.serialize_seq(Some(value.len()))?;
    for e in value {
        seq.serialize_element(e.as_ref())?;
    }
    seq.end()
}

这对我没有帮助,因为我遇到了同样的错误。我也试过:

impl Serialize for Arc<Category> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Category", 4)?;

        state.serialize_field("id", &self.id)?;
        state.serialize_field("name", &self.name)?;
        state.serialize_field("parent_id", &self.parent_id)?;
        state.serialize_field("children", &self.children)?;
        state.end();
    }
}

但这给出了错误 impl doesn't use types inside crate

我可能不用反序列化也能活下去,因为此时序列化更为重要。

Serde 为 Arc<T>Rc<T> 提供了 SerializeDeserialize 的实现,但前提是启用了 rc 功能。

Serde's reference website 上有一条评论解释了原因:

Opt into impls for Rc<T> and Arc<T>. Serializing and deserializing these types does not preserve identity and may result in multiple copies of the same data. Be sure that this is what you want before enabling this feature.

要启用 rc 功能,您需要在自己的 Cargo.toml:

中请求它
[dependencies]
serde = { version = "1.0", features = ["rc"] }