Skip to content

Commit

Permalink
Read json to obj
Browse files Browse the repository at this point in the history
  • Loading branch information
simsekgokhan committed Feb 10, 2024
1 parent d7a1de9 commit 6ae44c6
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(non_camel_case_types)]
#![allow(clippy::four_forward_slashes)]

// mod doc_test;
// todo: failed to resolve: use of undeclared crate or module `doc_test`
Expand Down
66 changes: 64 additions & 2 deletions src/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct City {
longitude: f64,
}

// 1.
// 1. Obj to json
#[test] fn ex1_to_json() {
let calabar = City {
name: String::from("Calabar"),
Expand Down Expand Up @@ -62,4 +62,66 @@ cbor (as UTF-8):
bincode (as UTF-8):
"\u{7}\0\0\0\0\0\0\0Calabar�+\u{7}\0\0\0\0\0������\u{13}@)\\���� @
*/
*/


// 2. json to obj

use serde_derive::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Person {
first_name: String,
last_name: String,
age: u8,
address: Address,
phone_numbers: Vec<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Address {
street: String,
city: String,
country: String,
}

#[test] fn ex2_from_json() {
let json = r#"{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"PhoneNumbers": [
"+44 1234567",
"+44 2345678"
]
}"#;

let person: Person = serde_json::from_str(json).expect("Invalid JSON");
println!("{:#?}", person);
/*
Person {
first_name: "John",
last_name: "Doe",
age: 43,
address: Address {
street: "Downing Street 10",
city: "London",
country: "Great Britain",
},
phone_numbers: [
"+44 1234567",
"+44 2345678",
],
}
*/

assert_eq!(person.first_name, "John");
assert_eq!(person.age, 43);
}

0 comments on commit 6ae44c6

Please sign in to comment.