Skip to content

Commit

Permalink
deserializes empty string into None Option (#607)
Browse files Browse the repository at this point in the history
Co-authored-by: Paul Mason <paul@paulmason.me>
  • Loading branch information
gai6948 and paupino authored Nov 14, 2023
1 parent ede308d commit 6cfccf3
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<E>(self, v: &str) -> Result<Self::Value, E>
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))
}
}
}
}

Expand Down Expand Up @@ -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]
Expand Down

0 comments on commit 6cfccf3

Please sign in to comment.