Module serde_with::rust::string_empty_as_none
source · Expand description
De/Serialize a Option<String>
type while transforming the empty string to None
Convert an Option<T>
from/to string using FromStr
and AsRef<str>
implementations.
An empty string is deserialized as None
and a None
vice versa.
Examples
#[derive(Deserialize, Serialize)]
struct A {
#[serde(with = "serde_with::rust::string_empty_as_none")]
tags: Option<String>,
}
let v: A = serde_json::from_str(r##"{
"tags": ""
}"##).unwrap();
assert!(v.tags.is_none());
let v: A = serde_json::from_str(r##"{
"tags": "Hi"
}"##).unwrap();
assert_eq!(Some("Hi".to_string()), v.tags);
let x = A {
tags: Some("This is text".to_string()),
};
assert_eq!(r#"{"tags":"This is text"}"#, serde_json::to_string(&x).unwrap());
let x = A {
tags: None,
};
assert_eq!(r#"{"tags":""}"#, serde_json::to_string(&x).unwrap());
Functions
Deserialize an
Option<T>
from a string using FromStr
Serialize a string from
Option<T>
using AsRef<str>
or using the empty string if None
.