我有一个包含自己类型的孩子的结构。这些孩子被包裹在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
我可能没有反序列化就可以生活,因为在这一点上序列化更重要。