尽管 rocket 和 serde 都列为依赖项,但无法使用 rocket::serde::json::Json

Unable to use rocket::serde::json::Json despite both rocket and serde listed as dependencies

我关注了quickstart guide。现在我正在尝试 return 一些超级简单的 JSON 并且文档是错误的并且没有进入 IRC 就无法提交票证。

错误

error[E0432]: unresolved import `rocket::serde::json`
 --> src/main.rs:2:20
  |
2 | use rocket::serde::json::Json;
  |                    ^^^^ could not find `json` in `serde`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `my-api` due to previous error

文件

Cargo.toml

[package]
name = "my-api"
version = "0.1.0"
edition = "2021"
publish = false

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rocket = "0.5.0-rc.1"
serde = "1.0.130"

main.rs

#[macro_use] extern crate rocket;
use rocket::serde::{Serialize, json::Json};

#[derive(Serialize)]
struct Location {
    lat: String,
    lng: String,
}

#[get("/?<lat>&<lng>")]
fn location(lat: &str, lng: &str) -> Json<Location> {
    Json(Location {
        lat: 111.1111.to_string(),
        lng: 222.2222.to_string(),
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![location])
}

如果你去 here 你会发现这几乎是来自文档的直接 copy/paste。我对 Rust 了解不够,无法解决依赖性错误。

rocketjson 功能需要在您的 Cargo.toml 中明确开启。

[package]
name = "my-api"
version = "0.1.0"
edition = "2018"  // cut back for testing with nixpkgs-provided rust
publish = false

[dependencies]
serde = "1.0.130"

[dependencies.rocket]
version = "0.5.0-rc.1"
features = ["json"]

这在 a comment in the Rocket source which generates the document here 中有记录。

在 Charles 的回答之上,我将 serde 导入更改为:

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

作为documented here