Skip to content

Commit

Permalink
added serialize_none_as_null for separate fields also
Browse files Browse the repository at this point in the history
  • Loading branch information
birhburh authored and knickish committed Sep 14, 2024
1 parent 0a4fccc commit 0902b6d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
5 changes: 3 additions & 2 deletions derive/src/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ pub fn derive_ser_json_struct(struct_: &Struct) -> TokenStream {

if field.ty.base() == "Option" {
let proxy_attr = crate::shared::attrs_proxy(&field.attributes);
let serialize_none_as_null_attr = shared::attrs_serialize_none_as_null(&struct_.attributes);
let null_on_none = serialize_none_as_null_attr && proxy_attr.is_none();
let struct_null_on_none = shared::attrs_serialize_none_as_null(&struct_.attributes);
let field_null_on_none = shared::attrs_serialize_none_as_null(&field.attributes);
let null_on_none = (field_null_on_none || struct_null_on_none) && proxy_attr.is_none();
let field_header = &format!("if first_field_was_serialized {{
s.conl();
}};
Expand Down
11 changes: 11 additions & 0 deletions tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,17 @@ fn ser_none_as_null() {
let b = Foo2 { x: None };

assert_eq!(SerJson::serialize_json(&b), r#"{"x":null}"#);

#[derive(SerJson)]
struct Foo3 {
x: Option<i32>,
#[nserde(serialize_none_as_null)]
y: Option<i32>,
}

let b = Foo3 { x: None, y: None };

assert_eq!(SerJson::serialize_json(&b), r#"{"y":null}"#);
}

#[test]
Expand Down

0 comments on commit 0902b6d

Please sign in to comment.