Deserializing Response body with Hyper?

I want to deserialize a json response body into a struct.. I'm only interested in some fields. How do I do this? I've already made a struct with the fields I'm interested in derive deserialize from serde, but I'm completely clueless on how to get the chunked response body into this. I don't even know how to print out the raw bytes..

You can do something like this:

use futures::stream::StreamExt; // for next()

let mut data = Vec::with_capacity(expected_length);
while let Some(chunk) = {
let parsed: MyType = serde_json::from_slice(&data)?;

You can obtain a value for the expected length by parsing the Content-Length header. Of course you can also just use Vec::new and allocate a few extra times.

1 Like

Oh! That works! Thank you so much!

I wanted to thank you for your reply also! I was under the impression that you could easy from_slice a &body, even though hyper's own example suggests a solution along the lines of yours. I just find it strange that I need to heap allocate each time I want to parse a body... but perhaps due to bodies stretching through multiple packets, it is reasonable.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.