Keep the old Response::into_json around and call this Response::into_json_deserialize

This commit is contained in:
Paolo Barbolini
2020-05-04 21:45:27 +02:00
committed by Martin Algesten
parent 0b69c595b6
commit 4e744f87c1
3 changed files with 63 additions and 6 deletions

View File

@@ -24,7 +24,8 @@ pub const DEFAULT_CHARACTER_SET: &str = "utf-8";
/// ///
/// The `Response` is used to read response headers and decide what to do with the body. /// The `Response` is used to read response headers and decide what to do with the body.
/// Note that the socket connection is open and the body not read until one of /// Note that the socket connection is open and the body not read until one of
/// [`into_reader()`](#method.into_reader), [`into_json()`](#method.into_json) or /// [`into_reader()`](#method.into_reader), [`into_json()`](#method.into_json),
/// [`into_json_deserialize()`](#method.into_json_deserialize) or
/// [`into_string()`](#method.into_string) consumes the response. /// [`into_string()`](#method.into_string) consumes the response.
/// ///
/// ``` /// ```
@@ -382,6 +383,32 @@ impl Response {
/// Example: /// Example:
/// ///
/// ``` /// ```
/// let resp =
/// ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json")
/// .call();
///
/// let json = resp.into_json().unwrap();
///
/// assert_eq!(json["hello"], "world");
/// ```
#[cfg(feature = "json")]
pub fn into_json(self) -> IoResult<serde_json::Value> {
let reader = self.into_reader();
serde_json::from_reader(reader).map_err(|e| {
IoError::new(
ErrorKind::InvalidData,
format!("Failed to read JSON: {}", e),
)
})
}
/// Turn the body of this response into a type implementing the (serde) Deserialize trait.
///
/// Requires feature `ureq = { version = "*", features = ["json"] }`
///
/// Example:
///
/// ```
/// # use serde::Deserialize; /// # use serde::Deserialize;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
@@ -393,12 +420,12 @@ impl Response {
/// ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json") /// ureq::get("https://ureq.s3.eu-central-1.amazonaws.com/hello_world.json")
/// .call(); /// .call();
/// ///
/// let json = resp.into_json::<Hello>().unwrap(); /// let json = resp.into_json_deserialize::<Hello>().unwrap();
/// ///
/// assert_eq!(json.hello, "world"); /// assert_eq!(json.hello, "world");
/// ``` /// ```
#[cfg(feature = "json")] #[cfg(feature = "json")]
pub fn into_json<T: DeserializeOwned>(self) -> IoResult<T> { pub fn into_json_deserialize<T: DeserializeOwned>(self) -> IoResult<T> {
let reader = self.into_reader(); let reader = self.into_reader();
serde_json::from_reader(reader).map_err(|e| { serde_json::from_reader(reader).map_err(|e| {
IoError::new( IoError::new(
@@ -730,6 +757,20 @@ mod tests {
#[test] #[test]
#[cfg(feature = "json")] #[cfg(feature = "json")]
fn parse_simple_json() { fn parse_simple_json() {
let s = "HTTP/1.1 200 OK\r\n\
\r\n\
{\"hello\":\"world\"}";
let resp = s.parse::<Response>().unwrap();
let v = resp.into_json().unwrap();
let compare = "{\"hello\":\"world\"}"
.parse::<serde_json::Value>()
.unwrap();
assert_eq!(v, compare);
}
#[test]
#[cfg(feature = "json")]
fn parse_deserialize_json() {
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -741,7 +782,7 @@ mod tests {
\r\n\ \r\n\
{\"hello\":\"world\"}"; {\"hello\":\"world\"}";
let resp = s.parse::<Response>().unwrap(); let resp = s.parse::<Response>().unwrap();
let v = resp.into_json::<Hello>().unwrap(); let v = resp.into_json_deserialize::<Hello>().unwrap();
assert_eq!(v.hello, "world"); assert_eq!(v.hello, "world");
} }

View File

@@ -61,6 +61,22 @@ fn body_as_text() {
#[test] #[test]
#[cfg(feature = "json")] #[cfg(feature = "json")]
fn body_as_json() { fn body_as_json() {
test::set_handler("/body_as_json", |_unit| {
test::make_response(
200,
"OK",
vec![],
"{\"hello\":\"world\"}".to_string().into_bytes(),
)
});
let resp = get("test://host/body_as_json").call();
let json = resp.into_json().unwrap();
assert_eq!(json["hello"], "world");
}
#[test]
#[cfg(feature = "json")]
fn body_as_json_deserialize() {
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -77,7 +93,7 @@ fn body_as_json() {
) )
}); });
let resp = get("test://host/body_as_json").call(); let resp = get("test://host/body_as_json").call();
let json = resp.into_json::<Hello>().unwrap(); let json = resp.into_json_deserialize::<Hello>().unwrap();
assert_eq!(json.hello, "world"); assert_eq!(json.hello, "world");
} }

View File

@@ -38,7 +38,7 @@ fn agent_set_cookie() {
assert_eq!(resp.status(), 200); assert_eq!(resp.status(), 200);
assert_eq!( assert_eq!(
"name=value", "name=value",
resp.into_json::<HttpBin>() resp.into_json_deserialize::<HttpBin>()
.unwrap() .unwrap()
.headers .headers
.get("Cookie") .get("Cookie")