首页 > 解决方案 > 如何使用rocket_contrib Json?

问题描述

我是 Rust 和 Rocket 的初学者。我试图通过阅读官方存储库中的示例来了解 Rocket。所以有一个例子叫content_type,里面有这样的描述// NOTE: In a real application, we'd use `rocket_contrib::json::Json`.

所以我尝试将 Json 与 Rocket_contrib 一起使用。该示例的代码如下所示。

#[macro_use] extern crate rocket;

#[cfg(test)] mod tests;

use std::io;

use rocket::request::Request;
use rocket::data::{Data, ToByteUnit};
use rocket::response::{Debug, content::{Json, Html}};

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}

#[get("/<name>/<age>", format = "json")]
fn get_hello(name: String, age: u8) -> Json<String> {
    // NOTE: In a real application, we'd use `rocket_contrib::json::Json`.
    let person = Person { name, age };
    Json(serde_json::to_string(&person).unwrap())
}

#[post("/<age>", format = "plain", data = "<name_data>")]
async fn post_hello(age: u8, name_data: Data) -> Result<Json<String>, Debug<io::Error>> {
    let name = name_data.open(64.bytes()).stream_to_string().await?;
    let person = Person { name, age };
    // NOTE: In a real application, we'd use `rocket_contrib::json::Json`.
    Ok(Json(serde_json::to_string(&person).expect("valid JSON")))
}

#[catch(404)]
fn not_found(request: &Request<'_>) -> Html<String> {
    let html = match request.format() {
        Some(ref mt) if !mt.is_json() && !mt.is_plain() => {
            format!("<p>'{}' requests are not supported.</p>", mt)
        }
        _ => format!("<p>Sorry, '{}' is an invalid path! Try \
                 /hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
                 request.uri())
    };

    Html(html)
}

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite()
        .mount("/hello", routes![get_hello, post_hello])
        .register(catchers![not_found])
}

另外,我转换的代码如下所示。

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;
extern crate rocket_contrib;
extern crate serde_json;

#[cfg(test)] mod tests;

use std::io::{self, Read};

use rocket::{Request, data::Data};
use rocket::response::{Debug, content::Html};

use rocket_contrib::json::Json;

#[derive(Debug, Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}

#[get("/<name>/<age>")]
fn get_hello(name: String, age: u8) -> Json<Person> {
    // NOTE: In a real application, we'd use `rocket_contrib::json::Json`.
    let person = Person { name: name, age: age, };
    // Json(serde_json::to_string(&person).unwrap())
    Json(person)
}

#[post("/<age>", format = "plain", data = "<name_data>")]
fn post_hello(age: u8, name_data: Data) -> Result<Json<String>, Debug<io::Error>> {
    let mut name = String::with_capacity(32);
    name_data.open().take(32).read_to_string(&mut name)?;
    let person = Person { name: name, age: age, };
    // NOTE: In a real application, we'd use `rocket_contrib::json::Json`.
    Ok(Json(serde_json::to_string(&person).expect("valid JSON")))
}

#[catch(404)]
fn not_found(request: &Request) -> Html<String> {
    let html = match request.format() {
        Some(ref mt) if !mt.is_json() && !mt.is_plain() => {
            format!("<p>'{}' requests are not supported.</p>", mt)
        }
        _ => format!("<p>Sorry, '{}' is an invalid path! Try \
                 /hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
                 request.uri())
    };

    Html(html)
}

fn main() {
    rocket::ignite()
        .mount("/hello", routes![get_hello, post_hello])
        .register(catchers![not_found])


我已阅读文档并补充说我需要#[derive(Debug, Serialize, Deserialize)]Person,但它不起作用。有什么问题?

错误如下所示。

error[E0277]: the trait bound `rocket_contrib::json::Json<Person>: rocket::response::Responder<'_>` is not satisfied
   --> examples/content_types/src/main.rs:34:40
    |
34  | fn get_hello(name: String, age: u8) -> Json<Person> {
    |                                        ^^^^^^^^^^^^ the trait `rocket::response::Responder<'_>` is not implemented for `rocket_contrib::json::Json<Person>`
    |
   ::: /Users/hikarukondo/Documents/Rocket/core/lib/src/handler.rs:202:20
    |
202 |     pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> {
    |                    ------------- required by this bound in `rocket::handler::<impl rocket::Outcome<rocket::Response<'r>, rocket::http::Status, rocket::Data>>::from`

error[E0277]: the trait bound `std::result::Result<rocket_contrib::json::Json<std::string::String>, rocket::response::Debug<std::io::Error>>: rocket::response::Responder<'_>` is not satisfied
   --> examples/content_types/src/main.rs:48:44
    |
48  | fn post_hello(age: u8, name_data: Data) -> Result<Json<String>, Debug<io::Error>> {
    |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `rocket::response::Responder<'_>` is not implemented for `std::result::Result<rocket_contrib::json::Json<std::string::String>, rocket::response::Debug<std::io::Error>>`
    |
   ::: /Users/hikarukondo/Documents/Rocket/core/lib/src/handler.rs:202:20
    |
202 |     pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> {
    |                    ------------- required by this bound in `rocket::handler::<impl rocket::Outcome<rocket::Response<'r>, rocket::http::Status, rocket::Data>>::from`
    |
    = help: the following implementations were found:
              <std::result::Result<R, E> as rocket::response::Responder<'r>>
              <std::result::Result<R, E> as rocket::response::Responder<'r>>

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0277`.
error: could not compile `content_types`.

To learn more, run the command again with --verbose.

标签: rustrust-rocket

解决方案


我想你忘了包括:

use serde::{Serialize, Deserialize};

推荐阅读