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 <wpcarro@gmail.com> Autosubmit: wpcarro <wpcarro@gmail.com> Tested-by: BuildkiteCI
This commit is contained in:
parent
c18ca0f852
commit
0ae6a441e6
2 changed files with 39 additions and 2 deletions
|
@ -5,3 +5,4 @@ edition = "2021"
|
|||
|
||||
[dependencies]
|
||||
serde_json = "1.0.81"
|
||||
serde = { version = "1.0.137", features = ["derive"] }
|
||||
|
|
|
@ -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()
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue