【问题标题】:Unable to use rocket::serde::json::Json despite both rocket and serde listed as dependencies尽管 Rocket 和 serde 都被列为依赖项,但无法使用 Rocket::serde::json::Json
【发布时间】:2021-12-26 07:24:17
【问题描述】:

我关注了quickstart guide。现在我正在尝试返回一些超级简单的 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,您会发现这几乎是文档的直接复制/粘贴。我对 Rust 的了解不够,无法解决依赖错误。

【问题讨论】:

    标签: rust rust-rocket


    【解决方案1】:

    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 中,它生成document here

    【讨论】:

    • 我认为如果它只出现在源文件的注释中,将其称为“已记录”是“不确定的”。
    • @KevinAnderson 该评论包含在生成的文档中:docs.rs
    • 好的,这很公平。我仍然会说它应该在你的 GitHub 上像你明确的 readme.md 这样的东西,但承认它比我最初想象的要高。
    • @KevinAnderson 非常感谢!如何获取文档以在我找到的位置记录 Cargo.toml 文件中的先决条件更改?
    • @kalm42, github.com/stackblitz/template-rust-rocket/blob/master/site/… 是提交 PR 的文件,如果你想这样做的话。我建议上述 PR 将该功能描述为可以选择启用的功能 - 仅显示它已启用,而没有评论这是一个 option 的方式,这与将其关闭的设计决定相悖-默认情况下,所以我不希望上游接受这样做的更改。
    【解决方案2】:

    在查尔斯的回答之上,我会将 serde 导入更改为:

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

    作为documented here

    【讨论】:

      猜你喜欢
      • 2022-09-24
      • 2019-03-30
      • 2021-09-19
      • 2021-02-26
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多