From 2e0bf984a34f6577591adbf33525d134f6390bb7 Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Thu, 1 Feb 2024 10:39:58 +0100 Subject: [PATCH] serde enum --- members/serde-json-demo/Cargo.toml | 1 + members/serde-json-demo/src/main.rs | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/members/serde-json-demo/Cargo.toml b/members/serde-json-demo/Cargo.toml index 165506e..33ad066 100644 --- a/members/serde-json-demo/Cargo.toml +++ b/members/serde-json-demo/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +anyhow = "1.0.79" chrono = { version = "0.4.26", features = ["serde"] } serde = { version = "1.0.171", features = ["derive"] } serde_json = "1.0.102" diff --git a/members/serde-json-demo/src/main.rs b/members/serde-json-demo/src/main.rs index a9d16a4..1f84d3c 100644 --- a/members/serde-json-demo/src/main.rs +++ b/members/serde-json-demo/src/main.rs @@ -1,6 +1,7 @@ use chrono; use serde::{Deserialize, Serialize}; use serde_json; +use anyhow; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[serde(rename_all = "UPPERCASE")] @@ -18,8 +19,16 @@ struct Qux { j: serde_json::Value, } -fn main() { - let qj = r#"{ +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(rename_all = "lowercase")] +enum Color { + Green, + Yellow, + Red, +} + +fn main() -> anyhow::Result<()> { + let qux_source = r#"{ "some Key": [1, 2, 3], "deep": { "m": true @@ -30,7 +39,7 @@ fn main() { q: Qux { i: 19, b: false, - j: serde_json::from_str(qj).unwrap(), + j: serde_json::from_str(qux_source).unwrap(), }, t: chrono::offset::Utc::now(), }; @@ -38,4 +47,11 @@ fn main() { println!("foo:\n\n{}", foostr); let foo2: Foo = serde_json::from_str(&foostr).unwrap(); println!("same?: {}", foo == foo2); + + let color_source = r#""yellow""#; + let color: Color = serde_json::from_str(color_source)?; + dbg!(&color); + let color_str = serde_json::to_string(&color)?; + dbg!(&color_str); + Ok(()) }