Sru*_*nde 3 json rust json-deserialization serde reqwest
我对 Rust 很陌生,我似乎无法找到这个问题的解决方案。我正在尝试以 json 形式获取 get 请求的响应。
#[macro_use]
extern crate serde;
extern crate serde_derive;
extern crate reqwest;
use reqwest::Error;
fn main(){
#[derive(Deserialize)]
struct Ip {
origin: String,
}
let json: Ip = reqwest::get("http://httpbin.org/ip").json();
//reqwest::get("http://httpbin.org/ip")?.json()?;
}
Run Code Online (Sandbox Code Playgroud)
这是cargo.toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_derive = "1.0"
reqwest = { version = "0.10", features = ["blocking"] }
Run Code Online (Sandbox Code Playgroud)
另外,如果我使用
reqwest::get("http://httpbin.org/ip")?.json()?;
Run Code Online (Sandbox Code Playgroud)
(添加问号)我收到另一个错误说
cannot use the `?` operator in a function that returns `()`
this function should return `Result` or `Option` to accept `?`
Run Code Online (Sandbox Code Playgroud)
我该如何解决这些问题?
根据文档,您需要在以下文件中启用jsonreqwest 功能Cargo.toml:
reqwest = { version = "0.10", features = ["blocking", "json"] }
Run Code Online (Sandbox Code Playgroud)
此外,reqwest::get是asyncAPI 的一部分。由于你main是同步的,你想要reqwest::blocking::get