diff --git a/.gitignore b/.gitignore index 65f1105..572aa44 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ # ---> Rust # Generated by Cargo # will have compiled files and executables -/target/ +target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html diff --git a/serde-json-test/Cargo.toml b/serde-json-test/Cargo.toml new file mode 100644 index 0000000..6acec42 --- /dev/null +++ b/serde-json-test/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "serde-json-test" +version = "0.1.0" +authors = ["Hatter Jiang "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" diff --git a/serde-json-test/src/main.rs b/serde-json-test/src/main.rs new file mode 100644 index 0000000..a484804 --- /dev/null +++ b/serde-json-test/src/main.rs @@ -0,0 +1,53 @@ +#[macro_use] +extern crate serde_json; + +use serde::{Deserialize, Serialize}; +use serde_json::{Result, Value}; + +// https://serde.rs/container-attrs.html +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +enum TestEnum { + + #[serde(rename = "A")] + TypeA, + + #[serde(rename = "B")] + TypeB, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct TestStruct { + ty: TestEnum, +} + +fn main() -> Result<()> { + let serialized = serde_json::to_string(&TestStruct{ + ty: TestEnum::TypeA, + }).unwrap(); + + println!("{}", serialized); + + let data = r#" + { + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }"#; + let v: Value = serde_json::from_str(data)?; + println!("{}", v); + + let john = json!({ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }); + println!("{}", john); + + Ok(()) +}