With the following code, I get an error when the incoming json has a null value for a field.
extern crate serde;
extern crate serde_aux;
extern crate serde_json;
use serde::{Deserialize, Serialize};
use serde_aux::prelude::*;
#[derive(Serialize, Deserialize, Debug, Default)]
struct MyStruct {
#[serde(deserialize_with = "deserialize_default_from_empty_object")]
name: String,
}
fn main() {
let s = r#" {"name": "George" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.name, "George");
let s = r#" { "name": {} } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.name, "");
let s = r#" { "name": null} "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.name, "");
}
The error is
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("data did not match any variant of untagged enum EmptyOrNot", line: 1, column: 16)', src/main.rs:38:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Strangely, enough the following code does not error, the name
field in MyStruct
is now wrapped in an Option
(as in the documentation example)
extern crate serde;
extern crate serde_aux;
extern crate serde_json;
use serde::{Deserialize, Serialize};
use serde_aux::prelude::*;
#[derive(Serialize, Deserialize, Debug, Default)]
struct MyStruct {
#[serde(deserialize_with = "deserialize_default_from_empty_object")]
name: Option<String>,
}
fn main() {
let s = r#" {"name": "George" }"#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.name, Some("George".to_owned()));
let s = r#" { "name": {} } "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.name, None);
let s = r#" { "name": null} "#;
let a: MyStruct = serde_json::from_str(s).unwrap();
assert_eq!(a.name, None);
}