diff --git a/Cargo.toml b/Cargo.toml index 6792780..a4382f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "serde_trim" -version = "0.2.0" +version = "0.3.0" authors = ["baoyachi "] edition = "2021" description = "serde deserialize_with String trim" diff --git a/README.md b/README.md index b7eb380..d881724 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ ## how to use ```rust fn main() { - #[derive(Debug, Deserialize)] + #[derive(Deserialize)] struct Foo { #[serde(deserialize_with = "string_trim")] name: String, @@ -20,5 +20,14 @@ fn main() { let json = r#"{"name":" "}"#; let foo = serde_json::from_str::(json).unwrap(); assert_eq!(foo.name, ""); + + #[derive(Deserialize)] + struct OptionFoo { + #[serde(deserialize_with = "option_string_trim")] + name: Option, + } + let json = r#"{"name":" "}"#; + let foo = serde_json::from_str::(json).unwrap(); + assert_eq!(foo.name, None); } ``` \ No newline at end of file diff --git a/lib.rs b/lib.rs index c7a729d..9f1029d 100644 --- a/lib.rs +++ b/lib.rs @@ -10,9 +10,22 @@ where Ok(de_string) } +pub fn option_string_trim<'de, D>(d: D) -> Result, D::Error> +where + D: de::Deserializer<'de>, +{ + let mut de_string: Option = Option::deserialize(d)?; + if let Some(ref mut de_string) = de_string { + if de_string.trim_in_place().is_empty() { + return Ok(None); + } + } + Ok(de_string) +} + #[test] fn test_string_trim() { - #[derive(Debug, Deserialize)] + #[derive(Deserialize)] struct Foo { #[serde(deserialize_with = "string_trim")] name: String, @@ -21,3 +34,15 @@ fn test_string_trim() { let foo = serde_json::from_str::(json).unwrap(); assert_eq!(foo.name, ""); } + +#[test] +fn test_option_string_trim() { + #[derive(Deserialize)] + struct OptionFoo { + #[serde(deserialize_with = "option_string_trim")] + name: Option, + } + let json = r#"{"name":" "}"#; + let foo = serde_json::from_str::(json).unwrap(); + assert_eq!(foo.name, None); +}