diff options
author | William Carroll <wpcarro@gmail.com> | 2022-06-27T01·03-0700 |
---|---|---|
committer | clbot <clbot@tvl.fyi> | 2022-06-27T18·07+0000 |
commit | 0ae6a441e6623e658271ddfcc1b5c33a1664079b (patch) | |
tree | f202e6f1b221906e06e05b30f53817b5dcdc0979 | |
parent | c18ca0f85262b3218ce6455c4071a880adb055bc (diff) |
feat(wpcarro/rust): Show 3/3 json examples r/4259
See git diff Change-Id: Ic3100dbed09775113ddb055e6ba0d5cf900426d0 Reviewed-on: https://cl.tvl.fyi/c/depot/+/5898 Reviewed-by: wpcarro <wpcarro@gmail.com> Autosubmit: wpcarro <wpcarro@gmail.com> Tested-by: BuildkiteCI
-rw-r--r-- | users/wpcarro/scratch/rust/json/Cargo.toml | 1 | ||||
-rw-r--r-- | users/wpcarro/scratch/rust/json/src/main.rs | 38 |
2 files changed, 38 insertions, 1 deletions
diff --git a/users/wpcarro/scratch/rust/json/Cargo.toml b/users/wpcarro/scratch/rust/json/Cargo.toml index ff4ed61e85e2..76235d11d37d 100644 --- a/users/wpcarro/scratch/rust/json/Cargo.toml +++ b/users/wpcarro/scratch/rust/json/Cargo.toml @@ -5,3 +5,4 @@ edition = "2021" [dependencies] serde_json = "1.0.81" +serde = { version = "1.0.137", features = ["derive"] } diff --git a/users/wpcarro/scratch/rust/json/src/main.rs b/users/wpcarro/scratch/rust/json/src/main.rs index e5f1078b5d01..1ec332705d0c 100644 --- a/users/wpcarro/scratch/rust/json/src/main.rs +++ b/users/wpcarro/scratch/rust/json/src/main.rs @@ -1,3 +1,4 @@ +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; // From the serde_json docs: @@ -17,6 +18,21 @@ use serde_json::{json, Value}; // // So let's take a look at all three... +//////////////////////////////////////////////////////////////////////////////// +// Types +//////////////////////////////////////////////////////////////////////////////// + +#[derive(Serialize, Deserialize, Debug)] +struct Person { + fname: String, + lname: String, + age: u8, +} + +//////////////////////////////////////////////////////////////////////////////// +// Functions +//////////////////////////////////////////////////////////////////////////////// + // 1) Reading/writing from/to plain text. // TL;DR: // - read: serde_json::from_str(data) @@ -48,6 +64,26 @@ fn two() { println!("result: {:?}", result); } +// 3) Parse into a strongly typed structure. +// TL;DR: +// - read: serde_json::from_str(data) +// - write: serde_json::to_string(x).unwrap() +fn three() { + let data = r#"{"fname":"William","lname":"Carroll","age":30}"#; + + let mut read: Person = serde_json::from_str(data).unwrap(); + read.fname = "Norm".to_string(); + read.lname = "Macdonald".to_string(); + read.age = 61; + + let write = serde_json::to_string(&read).unwrap(); + println!("result: {:?}", write); +} + +//////////////////////////////////////////////////////////////////////////////// +// Main +//////////////////////////////////////////////////////////////////////////////// + fn main() { - two() + three() } |