【问题标题】:Serializing sub properties on a struct doesn't seem to work序列化结构上的子属性似乎不起作用
【发布时间】:2019-07-21 14:52:54
【问题描述】:

我正在尝试序列化以下 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】:
    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 {
    

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2010-10-08
      • 1970-01-01
      • 2010-11-16
      • 2010-12-08
      • 2013-07-31
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      相关资源
      最近更新 更多