如何拆分来自 hyper JSON 正文的数据,以便我有一个包含多个键和值的哈希图?
How do I split up data from a hyper JSON body so I have a hashmap with multiple keys and values?
我已经设法使用以下方法从 hyper 中的 POST 方法中提取数据:
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server};
use std::convert::Infallible;
use std::net::SocketAddr;
use tokio;
async fn handle(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
match (_req.method(), _req.uri().path()) {
(&Method::GET, "/") => Ok(Response::new(Body::from("this is a get"))),
(&Method::POST, "/") => {
let byte_stream = hyper::body::to_bytes(_req).await?;
let _params = form_urlencoded::parse(&byte_stream)
.into_owned()
.collect::<HashMap<String, String>>();
然而,整个JSON主体现在只是HashMap
中的一个键。我如何拆分它以便我有一个包含多个键和值的哈希图,而不是一个键是整个主体?
[dependencies]
futures = "0.1"
hyper = "0.13"
pretty_env_logger = "0.3.1"
url = "2.1.1"
tokio = { version = "0.2", features = ["macros", "tcp"] }
bytes = "0.5"
您的描述有出入:
However, the whole JSON body
你的代码:
let _params = <strong><em>form_urlencoded</em></strong>::parse(&byte_stream)
如果您的数据是 JSON,则使用 serde_json
crate:
将其解析为 JSON
let _params: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
我已经设法使用以下方法从 hyper 中的 POST 方法中提取数据:
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server};
use std::convert::Infallible;
use std::net::SocketAddr;
use tokio;
async fn handle(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
match (_req.method(), _req.uri().path()) {
(&Method::GET, "/") => Ok(Response::new(Body::from("this is a get"))),
(&Method::POST, "/") => {
let byte_stream = hyper::body::to_bytes(_req).await?;
let _params = form_urlencoded::parse(&byte_stream)
.into_owned()
.collect::<HashMap<String, String>>();
然而,整个JSON主体现在只是HashMap
中的一个键。我如何拆分它以便我有一个包含多个键和值的哈希图,而不是一个键是整个主体?
[dependencies]
futures = "0.1"
hyper = "0.13"
pretty_env_logger = "0.3.1"
url = "2.1.1"
tokio = { version = "0.2", features = ["macros", "tcp"] }
bytes = "0.5"
您的描述有出入:
However, the whole JSON body
你的代码:
let _params = <strong><em>form_urlencoded</em></strong>::parse(&byte_stream)
如果您的数据是 JSON,则使用 serde_json
crate:
let _params: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();