как использовать rocket_contrib Json?

#rust #rust-rocket

#Ржавчина #rust-ракета

Вопрос:

Я новичок в 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(amp;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(amp;person).expect("valid JSON")))
}

#[catch(404)]
fn not_found(request: amp;Request<'_>) -> Html<String> {
    let html = match request.format() {
        Some(ref mt) if !mt.is_json() amp;amp; !mt.is_plain() => {
            format!("<p>'{}' requests are not supported.</p>", mt)
        }
        _ => format!("<p>Sorry, '{}' is an invalid path! Try 
                 /hello/amp;<nameamp;>/amp;<ageamp;> 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(amp;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(amp;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(amp;person).expect("valid JSON")))
}

#[catch(404)]
fn not_found(request: amp;Request) -> Html<String> {
    let html = match request.format() {
        Some(ref mt) if !mt.is_json() amp;amp; !mt.is_plain() => {
            format!("<p>'{}' requests are not supported.</p>", mt)
        }
        _ => format!("<p>Sorry, '{}' is an invalid path! Try 
                 /hello/amp;<nameamp;>/amp;<ageamp;> 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: amp;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: amp;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.
  

Ответ №1:

Я думаю, вы забыли включить:

 use serde::{Serialize, Deserialize};