about summary refs log tree commit diff
path: root/users/wpcarro/scratch/rust
diff options
context:
space:
mode:
Diffstat (limited to 'users/wpcarro/scratch/rust')
-rw-r--r--users/wpcarro/scratch/rust/json/Cargo.toml1
-rw-r--r--users/wpcarro/scratch/rust/json/src/main.rs38
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()
 }