错误[E0277]:不满足特征绑定`Request<Body>: serde::ser::Serialize`

error[E0277]: the trait bound `Request<Body>: serde::ser::Serialize` is not satisfied

我正在尝试将 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:?}");