我正在使用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",
我是做错了什么,还是这是意料之中的行为?
我将尝试在这里提供一个简单的示例。
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"]);
}
(操场(
将导致
"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"]);
它将打印出来:
John Doe 43岁