Reputation: 10733
I am making a GET call to some API which in turn would return me list
of JSON objects. However, I couldn't parse this into list of custom data structure.
Closest I could come to
struct Pokemon {
id: i32,
name: String,
height: i32,
weight: i32,
}
let mut response = client.get("http://pokeapi.co/api/v2/pokemon/111")
.send()
.expect("Failed to send request");
if let Ok(pokemon) = response.json::<Pokemon>() {
println!("{:#?}", pokemon);
}
Could anyone please provide me suitable example for same. Also, is this the standard way of doing it. I mean what difference would it make to use something like
let url = url.parse().expect("API URL parsing bug");
let request = Request::new(reqwest::Method::GET, url);
self.inner
.execute(request)
.map_err(Error::Request)
.and_then(move |response: Response| {
...
})
Upvotes: 0
Views: 67
Reputation: 3386
In order to use Response::json
, you must implement serde::Deserialize
for Pokemon
. You can do this by adding the following to your Cargo.toml, under [dependencies]
.
serde = { version = "1.0", features = ["derive"] }
Then, add use serde::Deserialize;
at the top of your file, and change the declaration of Pokemon
to:
#[derive(Deserialize)]
struct Pokemon {
id: i32,
name: String,
height: i32,
weight: i32,
}
Upvotes: 1