Repository: seanmonstar/reqwest (language: rust)

Issue:
Add a json method to Response
This would allow a user to write:

```rust
let thing: Thing = res.json()?;
```

The implementation would need to use `T: Deserialize` and `serde_json::from_reader`:

```rust
impl Response {
    pub fn json<T: Deserialize>(&mut self) -> ::Result<T> {
        // probably should check self.headers.get::<ContentType> for application/json
        serde_json::from_reader(&mut self).map_err(::Error::from)
    }
}
```


Discussion / hints:
I can try this one out if you haven't already started on it.

Go ahead!

What type of error would you like returned if the `Content-Type` is invalid or not included in the response? Would `hyper::error::Error::Header` suffice?


Fix patch:
diff --git a/src/client.rs b/src/client.rs
index 8f20346af..fba027ada 100644
--- a/src/client.rs
+++ b/src/client.rs
@@ -7,7 +7,7 @@ use hyper::status::StatusCode;
 use hyper::version::HttpVersion;
 use hyper::{Url};
 
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
 use serde_json;
 use serde_urlencoded;
 
@@ -275,6 +275,11 @@ impl Response {
     pub fn version(&self) -> &HttpVersion {
         &self.inner.version
     }
+
+    /// Try and deserialize the response body as JSON.
+    pub fn json<T: Deserialize>(&mut self) -> ::Result<T> {
+        serde_json::from_reader(self).map_err(::Error::from)
+    }
 }
 
 /// Read the body of the Response.
diff --git a/src/error.rs b/src/error.rs
index e78c13c3a..184189254 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -68,5 +68,11 @@ impl From<::serde_urlencoded::ser::Error> for Error {
     }
 }
 
+impl From<::serde_json::Error> for Error {
+    fn from(err: ::serde_json::Error) -> Error {
+        Error::Serialize(Box::new(err))
+    }
+}
+
 /// A `Result` alias where the `Err` case is `reqwest::Error`.
 pub type Result<T> = ::std::result::Result<T, Error>;


Test patch: