【问题标题】:json method not found when Deserializing a reqwest response反序列化 reqwest 响应时找不到 json 方法
【发布时间】:2020-05-06 07:17:22
【问题描述】:

我对 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"] }

我不断收到的错误是

另外, 如果我使用

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 `?`

我该如何解决这些问题?

【问题讨论】:

  • 请附上您收到的错误文本,而不是屏幕截图。
  • 请发送正确的minimal reproducible example。在这里指明reqwest 的具体版本可能很重要。

标签: json rust json-deserialization serde reqwest


【解决方案1】:

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

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

另外,reqwest::getasync API 的一部分。由于您的main 是同步的,因此您需要reqwest::blocking::get

【讨论】:

  • 查看编辑后的答案:您可能想要reqwest::blocking::get 而不是reqwest::get
  • 哪个错误?您的问题包含两条错误消息。我的回答应该解决第一个问题,第二个是duplicate