From be1e64dbcb69a9a33ff7ceca1b908c18852259d3 Mon Sep 17 00:00:00 2001 From: Lorenzo Leonardo Date: Sun, 24 Mar 2024 20:31:28 +0800 Subject: [PATCH] feat: added JsonElem::Null --- src/jsonelem.rs | 2 ++ src/test.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/jsonelem.rs b/src/jsonelem.rs index 4843f7f..791c6a3 100644 --- a/src/jsonelem.rs +++ b/src/jsonelem.rs @@ -8,6 +8,7 @@ use crate::error::Error; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged)] pub enum JsonElem { + Null, Integer(i32), Float(f64), Bool(bool), @@ -71,6 +72,7 @@ impl TryInto> for JsonElem { impl Display for JsonElem { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + JsonElem::Null => write!(f, "{}", JsonElem::Null), JsonElem::Integer(val) => write!(f, "{}", val), JsonElem::Float(val) => write!(f, "{}", val), JsonElem::Bool(val) => write!(f, "{}", val), diff --git a/src/test.rs b/src/test.rs index c9e4452..dcdd4bc 100644 --- a/src/test.rs +++ b/src/test.rs @@ -331,3 +331,30 @@ fn test_from_jsonelem_to_json_slice() { let result: Vec = given.try_into().unwrap(); assert_eq!(expected, result.as_slice()); } + +#[test] +fn test_null() { + #[derive(Serialize, Deserialize, Debug, PartialEq)] + struct CallMethod { + object: String, + method: String, + param: JsonElem, + } + + let call = CallMethod { + object: "my_object".to_string(), + method: "my_function".to_string(), + param: JsonElem::Null, + }; + assert_eq!( + r#"{"object":"my_object","method":"my_function","param":null}"#.to_string(), + serde_json::to_string(&call).unwrap() + ); + + let output = serde_json::from_slice::( + r#"{"object":"my_object","method":"my_function","param":null}"#.as_bytes(), + ) + .unwrap(); + + assert_eq!(call, output); +}