gpt4 book ai didi

json - 错误[E0277] : the trait bound `Request: serde::ser::Serialize` is not satisfied

转载 作者:行者123 更新时间:2023-12-05 05:42:59 25 4
gpt4 key购买 nike

我正在尝试将 Hyper HTTP 请求对象输出为 JSON。我正在使用 Serde 将对象序列化为 JSON。

因为我没有定义 HTTP 请求结构,所以我不能向它添加属性 #[derive(Serialize, Deserialize)]。关于如何解决这个问题的任何想法?

我的代码:

use hyper::body::HttpBody as _;    
use hyper::{Body, Client, Method, Request, Uri};
use hyper_tls::HttpsConnector;
#[cfg(feature = "std")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{json, Result as re_, Value};
use tokio::io::{stdout, AsyncWriteExt as _};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let https = HttpsConnector::new();

// Client Object
let client = Client::builder().build::<_, hyper::Body>(https);
let uri: Uri = "https://api.api.com".parse()?;
let http_body = String::from(" body");
let content_length = http_body.chars().count();
//Build Request
let req = Request::builder()
.method(Method::POST)
.uri(uri)
.header("accept", "application/xml")
.header("content-type", "application/xml")
.header("Content-Length", content_length)
.body(Body::from(http_body))?;

// Serialize it to a JSON string.
let j = serde_json::to_string(&req)?;

// Print HTTP Request
println!("{}", j);

// Await the response...
let mut resp = client.request(req).await?;
println!("Response: {}", resp.status());
Ok(())
}

堆栈跟踪显示:

|     let j = serde_json::to_string(&req)?;
| --------------------- ^^^^ the trait `serde::ser::Serialize` is not implemented for `Request<Body>`
| |
| required by a bound introduced by this call
|
note: required by a bound in `serde_json::to_string`
--> /home/joel/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.79/src/ser.rs:2225:17
|
2225 | T: ?Sized + Serialize,
| ^^^^^^^^^ required by this bound in `serde_json::to_string`

cargo .toml

[dependencies]
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
serde_derive = "1.0.136"
hyper = { version = "0.14.18", features = ["full"] }
tokio = { version = "1.17.0", features = ["full"] }
hyper-tls = "0.5.0"
rustls = "0.20.4"

最佳答案

如果你想为外部 crate 派生 de/serialize,你可以遵循官方 serde guide为此。

此外,如果您只是为了打印而尝试序列化它,也许您可​​以考虑在包装器上编写或使用默认的 DebugDisplay 实现。默认的 Debug 可能会做:

// Print HTTP Request
println!("{req:?}");

关于json - 错误[E0277] : the trait bound `Request<Body>: serde::ser::Serialize` is not satisfied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71904465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com