From 0ae6a441e6623e658271ddfcc1b5c33a1664079b Mon Sep 17 00:00:00 2001 From: William Carroll Date: Sun, 26 Jun 2022 18:03:16 -0700 Subject: [PATCH] feat(wpcarro/rust): Show 3/3 json examples See git diff Change-Id: Ic3100dbed09775113ddb055e6ba0d5cf900426d0 Reviewed-on: https://cl.tvl.fyi/c/depot/+/5898 Reviewed-by: wpcarro Autosubmit: wpcarro Tested-by: BuildkiteCI --- users/wpcarro/scratch/rust/json/Cargo.toml | 1 + users/wpcarro/scratch/rust/json/src/main.rs | 40 +++++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/users/wpcarro/scratch/rust/json/Cargo.toml b/users/wpcarro/scratch/rust/json/Cargo.toml index ff4ed61e8..76235d11d 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 e5f1078b5..1ec332705 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); } -fn main() { - two() +// 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() { + three() }