JSON响应的反序列化在字符串中保留引号

7

我正在使用reqwest查询Google API:

let request_url = format!(
    "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=*\
     &inputtype=textquery\
     &fields=formatted_address,name,place_id,types\
     &locationbias=circle:50@{},{}\
     &key=my-secret-key",
    lat, lng
);

let mut response = reqwest::get(&request_url).expect("pffff");

let gr: GoogleResponse = response.json::<GoogleResponse>().expect("geeez");

GoogleResponse 结构体定义如下:

#[derive(Debug, Serialize, Deserialize)]
pub struct DebugLog {
    pub line: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Candidate {
    pub formatted_address: String,
    pub name: String,
    pub place_id: String,
    pub types: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GoogleResponse {
    pub candidates: Vec<Candidate>,
    pub debug_log: DebugLog,
    pub status: String,
}

这段代码已经编译通过,我可以发出请求,但是我的String字段中的结果包含原始的"。这是正常情况吗?
例如,在打印格式化地址时,我得到了以下结果:
"result": "\"Street blabh blahab blahb\"",

当我真正想要的只是

"result": "Street blabh blahab blahb",

我做错了什么还是这是预期的行为?

2
将来请提供一个适当的 MCVE,在其中以最小的方式描述您的问题并让我们看到一些代码。 - hellow
1个回答

11

我将在这里提供一个简单的例子。

extern crate serde; // 1.0.80
extern crate serde_json; // 1.0.33

use serde_json::Value;

const JSON: &str = r#"{
  "name": "John Doe",
  "age": 43
}"#;

fn main() {
    let v: Value = serde_json::from_str(JSON).unwrap();
    println!("{} is {} years old", v["name"], v["age"]);
}

(playground)

将会导致

"John Doe" 今年 43 岁

原因是,v["name"] 不是一个 String,而是一个 Value(你可以通过添加 let a: () = v["name"]; 这一行来检查,这将导致错误:expected (), found enum 'serde_json::Value')。

如果你想要一个 &str/String,你需要先使用 Value::as_str 进行转换。

如果你相应地更改 println! 行:

println!("{} is {} years old", v["name"].as_str().unwrap(), v["age"]);

它将打印出:

约翰·多伊今年43岁


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接