首页 > 解决方案 > Rust/Rocket:没有为结构实现特征 `serde::ser::Serialize`

问题描述

我正在尝试使用 Rocket 制作一个简单的端点。我Cargo.toml有这些依赖项:

[dependencies]
rocket = "0.4.2"
rocket_codegen = "0.4.2"
rocket_contrib = "0.4.2"

main.rs好像:

#[macro_use]
extern crate rocket;

use rocket_contrib::json::Json;
use serde::Serialize;

#[get("/org")]
fn getorg() -> Json<Org> {
    Json(Org {
        id: Option::from(25),
        name: "Incredible-Customer".to_string(),
    })
}
#[derive(Serialize)]
pub struct Org {
    pub id: Option<i32>,
    pub name: String,
}

fn main() {
    rocket::ignite().mount("/", routes![getorg]).launch();
}

编译导致错误:

error[E0432]: unresolved import `serde`
 --> src/main.rs:3:5
  |
3 | use serde::Serialize;
  |     ^^^^^ use of undeclared crate or module `serde`

error: cannot determine resolution for the derive macro `Serialize`
  --> src/main.rs:14:10
   |
14 | #[derive(Serialize)]
   |          ^^^^^^^^^
   |
   = note: import resolution is stuck, try simplifying macro imports

error[E0658]: `macro` is experimental
 --> src/main.rs:7:1
  |
7 | #[get("/org")]
  | ^^^^^^^^^^^^^^
  |
  = note: see issue #39412 <https://github.com/rust-lang/rust/issues/39412> for more information
  = help: add `#![feature(decl_macro)]` to the crate attributes to enable
  = note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0277]: the trait bound `Org: serde::ser::Serialize` is not satisfied
   --> src/main.rs:8:16
    |
8   | fn getorg() -> Json<Org> {
    |                ^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `Org`
    |
   ::: /Users/shep/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/handler.rs:202:20
    |
202 |     pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> {
    |                    ------------- required by this bound in `handler::<impl rocket::Outcome<rocket::Response<'r>, rocket::http::Status, rocket::Data>>::from`
    |
    = note: required because of the requirements on the impl of `Responder<'_>` for `rocket_contrib::json::Json<Org>

我对如何查看此错误感到非常困惑。是依赖问题吗?为什么?我已将rocket依赖项版本化为相同的版本,但显然这种serde依赖项并不令人满意。谷歌搜索声称这是我的一个依赖项中的版本不匹配 - 但我该如何自己解决这个问题?

标签: rustrust-rocket

解决方案


serde = {version = "1.0", features = ["derive"]}将and添加serde_json = {version = "1.0"}到您cargo.toml的可以衍生自SerializeandDeserialize


推荐阅读