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.
Converting to serde_as
The same functionality can be more clearly expressed via NoneAsEmptyString and using the serde_as macro.
#[serde_as]
#[derive(Deserialize)]
struct A {
    #[serde_as(as = "NoneAsEmptyString")]
    value: Option<String>,
}Examples
#[derive(Deserialize, Serialize)]
struct A {
    #[serde(with = "string_empty_as_none")]
    tags: Option<String>,
}
let v: A = serde_json::from_value(json!({ "tags": "" })).unwrap();
assert_eq!(None, v.tags);
let v: A = serde_json::from_value(json!({ "tags": "Hi" })).unwrap();
assert_eq!(Some("Hi".to_string()), v.tags);
let x = A {
    tags: Some("This is text".to_string()),
};
assert_eq!(json!({ "tags": "This is text" }), serde_json::to_value(&x).unwrap());
let x = A {
    tags: None,
};
assert_eq!(json!({ "tags": "" }), serde_json::to_value(&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.