Hyper: Guide request: Example of using serde_json to parse the body of a response

Created on 29 Jun 2017  路  4Comments  路  Source: hyperium/hyper

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.

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:

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.

All 4 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FGRibreau picture FGRibreau  路  4Comments

gabisurita picture gabisurita  路  4Comments

belst picture belst  路  3Comments

crackcomm picture crackcomm  路  5Comments

fabioberger picture fabioberger  路  5Comments