gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:35:13 24 4
gpt4 key购买 nike

我正在使用 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"]);
}

( playground )

将导致

"John Doe" is 43 years old

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

如果你想要一个&str/String,你必须先用Value::as_str转换它.

如果相应地更改 println! 行:

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

它会打印出:

John Doe is 43 years old

关于json - JSON响应的反序列化在字符串中保留引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53378780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com