From the reqwest docs, you can get the deserialized json, or the body text from a request response.
What I can't see is how to get them both. My requirement is that I want the decoded json for use in the code but want to print out the text for debugging. Unfortunately attempting to get both will give you an error about use of a moved value since both of these functions take ownership of the request. It doesn't seem possible to clone the request either.
This is an example of something I'd like to be able to do but line 4 is invalid since it uses response which was moved on line 1.
let posts: Vec<Post> = match response.json::<PostList>().await {
Ok(post_list) => post_list.posts,
Err(e) => {
let text = response.text().await.unwrap();
println!("Error fetching posts: {}, {}", e, text);
Vec::new()
}
};
Response::json()
method is literally just getting the bytes of the response body and then callingserde_json::from_slice
on that. What's stopping you from doing the same thing? Get thetext()
, print it, then deserialize the text as JSON. – Alyworthposts
object directly, assuming it implementsDebug
orDisplay
. – Alyworth