Skip to content

Instantly share code, notes, and snippets.

@gothburz
Created October 15, 2023 05:09
Show Gist options
  • Save gothburz/f97d8001735c2889a1e39512c479d89d to your computer and use it in GitHub Desktop.
Save gothburz/f97d8001735c2889a1e39512c479d89d to your computer and use it in GitHub Desktop.
Demo on how to deserialize JSON with HashMap & serde_json::Value in Rust lang.
use reqwest;
use serde_json;
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// KNOWN RETURN - HashMap
const URL2: &str = "https://httpbin.org/ip";
match reqwest::get(URL2).await {
Ok(resp) => {
let json = resp.json::<HashMap<String, String>>().await?;
println!("{:?}", json)
}
Err(err) => {
println!("Reqwest Error: {}", err)
}
}
// UNKNOWN RETURN - serde_json::Value
const URL1: &str = "https://dummyjson.com/products/1";
match reqwest::get(URL1).await {
Ok(resp) => {
let json: serde_json::Value = resp.json().await?;
println!("{:?}", json)
}
Err(err) => {
println!("Reqwest Error: {}", err)
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment