反序列化 reqwest 响应时找不到 json 方法

标签 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()?;
}

这是 cargo.toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_derive = "1.0"
reqwest = { version = "0.10", features = ["blocking"] }

我不断收到的错误是
json error

还,
如果我使用
reqwest::get("http://httpbin.org/ip")?.json()?;

(添加问号)
我收到另一个错误说
cannot use the `?` operator in a function that returns `()`
this function should return `Result` or `Option` to accept `?`

我该如何解决这些问题?

最佳答案

根据 doc ,您需要启用json Cargo.toml 中的 reqwest 功能:

reqwest = { version = "0.10", features = ["blocking", "json"] }

另外, reqwest::get async 的一部分API。由于您的main是同步的,你想要 reqwest::blocking::get

关于反序列化 reqwest 响应时找不到 json 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61629447/

相关文章:

java - 如何在GWT中使用autobean将json转换为java类

流行的 Linux 发行版中的 C/JSON 库?

java - 按降序对 jsonarray 数据进行排序

asynchronous - Rust 解构枚举受 std::sync::RwLock 保护,返回引用

vector - 如何访问新类型的向量作为基础类型

rust - 是否可以检查 rust 的闭合度是否相等?

c# - 处理json反序列化错误

json - REST API 和安全性

php - 如何正确使用 JSON.stringify 和 json_decode()

arrays - 如何表示 EVReflection 的嵌套数组类型