如何使用rocket_contrib Json?

问题描述

我是铁锈和火箭的初学者。 我试图通过阅读官方存储库中的示例来了解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,}

#[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>",data = "<name_data>")]
fn post_hello(age: u8,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,};
    // 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>",request.uri())
    };

    Html(html)
}

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


我已阅读文档,并补充说我需要#[derive(Debug,Deserialize)] for 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,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,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.

解决方法

我认为您忘了包括:

ImportError: No module named myModule.main