It'd be awesome if there was an example in the hyper guide of using serde_json to parse the body of a response. Making their different types play nice with each other is proving non-obvious to me.
Here's (seemingly) relevant code in reqwest: https://github.com/seanmonstar/reqwest/blob/855e6615eb553feab5d382c2017ad76e82560768/src/async_impl/response.rs#L109-L122
The difficult part here seems to be coming up with a minimal example for this
A similar issue was discussed in https://github.com/hyperium/hyper/issues/1137, but it has changed a bit. Here is what I do:
response.body().concat2().and_then(move |body: Chunk| {
let foo = serde_json::from_slice::<Foo>(&body).unwrap();
}
A hyper::Body is a _stream_ of hyper::Chunk, so we need a non-blocking way to get all the chunks before we parse the json. The concat2() function takes the separate body chunks and makes one hyper::Chunk value. Once we have a chunk that contains the entire body contents, we can leverage the fact that hyper::Chunk can be converted via AsRef into a slice of bytes ([u8]). We can then use the serde_json::from_slice() function to deserialize the bytes into an example Foo struct.
I am willing to improve/expand on this and make a PR to https://github.com/hyperium/hyperium.github.io/blob/master/_guides/client/basic.md if it will be accepted.
That snippet is basically what I landed on, but it definitely took a lot of docs reading to get there! Just having that exact snippet in the guides would have been a huge help, so 馃憤 from me.
I put my first draft up here: https://github.com/hyperium/hyperium.github.io/pull/8. Feedback is appreciated!
Most helpful comment
A similar issue was discussed in https://github.com/hyperium/hyper/issues/1137, but it has changed a bit. Here is what I do:
A
hyper::Bodyis a _stream_ ofhyper::Chunk, so we need a non-blocking way to get all the chunks before we parse the json. Theconcat2()function takes the separate body chunks and makes onehyper::Chunkvalue. Once we have a chunk that contains the entire body contents, we can leverage the fact thathyper::Chunkcan be converted viaAsRefinto a slice of bytes ([u8]). We can then use theserde_json::from_slice()function to deserialize the bytes into an exampleFoostruct.I am willing to improve/expand on this and make a PR to https://github.com/hyperium/hyperium.github.io/blob/master/_guides/client/basic.md if it will be accepted.