Added JSON examples
This commit is contained in:
committed by
Sean McArthur
parent
3a5af68b92
commit
276c3d6594
40
examples/json_dynamic.rs
Normal file
40
examples/json_dynamic.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! This example illustrates the way to send and receive arbitrary JSON.
|
||||
//!
|
||||
//! This is useful for some ad-hoc experiments and situations when you don't
|
||||
//! really care about the structure of the JSON and just need to display it or
|
||||
//! process it at runtime.
|
||||
extern crate reqwest;
|
||||
#[macro_use] extern crate serde_json;
|
||||
|
||||
fn main() -> Result<(), reqwest::Error> {
|
||||
let echo_json: serde_json::Value = reqwest::Client::new()
|
||||
.post("https://jsonplaceholder.typicode.com/posts")
|
||||
.json(
|
||||
&json!({
|
||||
"title": "Reqwest.rs",
|
||||
"body": "https://docs.rs/reqwest",
|
||||
"userId": 1
|
||||
})
|
||||
)
|
||||
.send()?
|
||||
.json()?;
|
||||
|
||||
println!("{:#?}", echo_json);
|
||||
// Object(
|
||||
// {
|
||||
// "body": String(
|
||||
// "https://docs.rs/reqwest"
|
||||
// ),
|
||||
// "id": Number(
|
||||
// 101
|
||||
// ),
|
||||
// "title": String(
|
||||
// "Reqwest.rs"
|
||||
// ),
|
||||
// "userId": Number(
|
||||
// 1
|
||||
// )
|
||||
// }
|
||||
// )
|
||||
Ok(())
|
||||
}
|
||||
42
examples/json_typed.rs
Normal file
42
examples/json_typed.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
//! This example illustrates the way to send and receive statically typed JSON.
|
||||
//!
|
||||
//! In contrast to the arbitrary JSON example, this brings up the full power of
|
||||
//! Rust compile-time type system guaranties though it requires a little bit
|
||||
//! more code.
|
||||
extern crate reqwest;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
extern crate serde_json;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Post {
|
||||
id: Option<i32>,
|
||||
title: String,
|
||||
body: String,
|
||||
#[serde(rename = "userId")]
|
||||
user_id: i32,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), reqwest::Error> {
|
||||
let new_post = Post {
|
||||
id: None,
|
||||
title: "Reqwest.rs".into(),
|
||||
body: "https://docs.rs/reqwest".into(),
|
||||
user_id: 1
|
||||
};
|
||||
let new_post: Post = reqwest::Client::new()
|
||||
.post("https://jsonplaceholder.typicode.com/posts")
|
||||
.json(&new_post)
|
||||
.send()?
|
||||
.json()?;
|
||||
|
||||
println!("{:#?}", new_post);
|
||||
// Post {
|
||||
// id: Some(
|
||||
// 101
|
||||
// ),
|
||||
// title: "Reqwest.rs",
|
||||
// body: "https://docs.rs/reqwest",
|
||||
// user_id: 1
|
||||
// }
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user