requests-rs
requests-rs copied to clipboard
Add Serde support
If I know what the response body looks like, I want to be able to do something like:
#[derive(Deserialize)]
struct MyResponse {
user: String,
commits: Vec<Commit>,
}
fn main() {
let resp: requests::Response = /* ... */;
let body: MyResponse = resp.json().unwrap();
}
The implementation would look something like:
impl Response {
/* ... */
pub fn json<T>(&self) -> serde_json::Result<T> where T: Deserialize {
serde_json::from_str(self.text().unwrap())
}
}
It used to be that way once - https://github.com/imp/requests-rs/commit/ed5e85abe98bf875d2a8647881d4be5c9ae09ee4#diff-6cfc163228cc31bed4a7214fa0b69300L66. May be it is time to re-introduce serde support back, as a feature. Let me play with it a bit.
Thanks. For me the overwhelmingly common case is knowing what response I expect, so having to deal with an untyped JsonValue is bad. In the rare case that I don't know, I don't have a preference between json::JsonValue vs serde_json::Value.
Serde's #[derive(Deserialize)] now works in the most recent stable compiler so this would be a good time to support it.
@dtolnay Thanks for pinging me. serde support is under way in serde branch
Nice! Let me know if you would like me to review the changes when you think the branch is ready.
It looks like the current code on the serde branch is only using serde_json::Value which forfeits most of the advantages of Serde. I would like to be able to get back the response as any type T defined in my program.
let body: MyResponseType = resp.json().unwrap();
Correct. And that is the reason I've said it is under way, rather that complete and ready to go :)