序列化结构上的子属性似乎不起作用

问题描述 投票:1回答:1

我正在尝试序列化以下Result对象,但是我收到错误,因为虽然它适用于某些属性,但它似乎不适用于path,即使所有涉及的元素都有implementations provided by Serde

#[macro_use]
extern crate serde;
extern crate rocket;

use rocket_contrib::json::Json;
use std::rc::Rc;

#[derive(Serialize)]
struct Result {
    success: bool,
    path: Vec<Rc<GraphNode>>,
    visited_count: u32,
}
struct GraphNode {
    value: u32,
    parent: Option<Rc<GraphNode>>,
}

fn main(){}

fn index() -> Json<Result> {
    Json(Result {
        success: true,
        path: vec![],
        visited_count: 1,
    })
}

Playground,虽然我不能让它拉入火箭箱,但它绝不是最受欢迎的100个之一。

error[E0277]: the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
  --> src/main.rs:11:5
   |
11 |     path: Vec<Rc<GraphNode>>,
   |     ^^^^ the trait `serde::Serialize` is not implemented for `std::rc::Rc<GraphNode>`
   |
   = note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
   = note: required by `serde::ser::SerializeStruct::serialize_field`

根据我的理解,#[derive(Serialize)]应该自动创建一个serde可以使用的序列化方法。但是我希望它也可以用于物业。我是否需要为所有类型创建结构,然后为所有结构派生Serialize

我需要做些什么来启用它吗?

以下板条箱正在使用中:

rocket = "*" 
serde = { version = "1.0", features = ["derive"] } 
rocket_contrib = "*"
rust serde
1个回答
3
投票
the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied

这意味着Rc没有实现Serialize。见How do I serialize or deserialize an Arc<T> in Serde?。 TL; DR:

serde = { version = "1.0", features = ["derive", "rc"] }

添加后,错误消息将更改为:

error[E0277]: the trait bound `GraphNode: serde::Serialize` is not satisfied
  --> src/main.rs:11:5
   |
11 |     path: Vec<Rc<GraphNode>>,
   |     ^^^^ the trait `serde::Serialize` is not implemented for `GraphNode`
   |
   = note: required because of the requirements on the impl of `serde::Serialize` for `std::rc::Rc<GraphNode>`
   = note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
   = note: required by `serde::ser::SerializeStruct::serialize_field`

那是因为每个需要序列化的类型必须实现Serialize

#[derive(Serialize)]
struct GraphNode {
© www.soinside.com 2019 - 2024. All rights reserved.