about summary refs log tree commit diff
path: root/users/wpcarro/scratch/rust/json/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'users/wpcarro/scratch/rust/json/src/main.rs')
-rw-r--r--users/wpcarro/scratch/rust/json/src/main.rs38
1 files changed, 37 insertions, 1 deletions
diff --git a/users/wpcarro/scratch/rust/json/src/main.rs b/users/wpcarro/scratch/rust/json/src/main.rs
index e5f1078b5d..1ec332705d 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()
 }