首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用rocket_contrib Json?

如何使用rocket_contrib Json?
EN

Stack Overflow用户
提问于 2020-08-16 02:19:55
回答 1查看 2.2K关注 0票数 4

我是生锈和火箭的初学者。我试图通过阅读官方存储库中的例子来理解火箭。因此,有一个名为content_type的示例,其中有一个像// NOTE: In a real application, we'd use `rocket_contrib::json::Json`.这样的描述。

所以我尝试在rocket_contrib中使用Json。该示例的代码如下所示。

代码语言:javascript
复制
#[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])
}

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

代码语言:javascript
复制
#![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)],但是它不起作用。有什么问题吗?

错误如下所示。

代码语言:javascript
复制
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.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-26 00:31:42

我想你忘了包括:

代码语言:javascript
复制
use serde::{Serialize, Deserialize};
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63432521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档