From 6cfccf3980fe204ecd333370fefb596d1b5127ae Mon Sep 17 00:00:00 2001 From: gaius <61444500+gai6948@users.noreply.github.com> Date: Tue, 14 Nov 2023 08:57:48 +0800 Subject: [PATCH] deserializes empty string into None Option (#607) Co-authored-by: Paul Mason --- src/serde.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/serde.rs b/src/serde.rs index c423772..993b008 100644 --- a/src/serde.rs +++ b/src/serde.rs @@ -426,7 +426,22 @@ impl<'de> serde::de::Visitor<'de> for OptionDecimalStrVisitor { where D: serde::de::Deserializer<'de>, { - d.deserialize_str(DecimalVisitor).map(Some) + d.deserialize_str(Self) + } + + fn visit_str(self, v: &str) -> Result + where + E: serde::de::Error, + { + match v.is_empty() { + true => Ok(None), + false => { + let d = Decimal::from_str(v) + .or_else(|_| Decimal::from_scientific(v)) + .map_err(serde::de::Error::custom)?; + Ok(Some(d)) + } + } } } @@ -843,6 +858,12 @@ mod test { let deserialized: StringExample = serde_json::from_str(r#"{"value":null}"#).unwrap(); assert_eq!(deserialized.value, original.value); assert!(deserialized.value.is_none()); + + // Empty string deserialization tests + let original = StringExample { value: None }; + let deserialized: StringExample = serde_json::from_str(r#"{"value":""}"#).unwrap(); + assert_eq!(deserialized.value, original.value); + assert!(deserialized.value.is_none()); } #[test]