gpt4 book ai didi

rust - 如何在 Serde 中序列化或反序列化 Arc

转载 作者:行者123 更新时间:2023-11-29 07:44:09 36 4
gpt4 key购买 nike

我有一个包含自己类型子项的结构。这些 child 被包裹在Arc s,我在调用 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 提供了 Serialize 的实现和 Deserialize对于 Arc<T>Rc<T> , 但前提是 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"] }

关于rust - 如何在 Serde 中序列化或反序列化 Arc<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312600/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com