Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

serde_json: serialize None as null if there is default attribute #111

Merged
merged 3 commits into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions derive/src/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,42 @@ pub fn derive_ser_json_struct(struct_: &Struct) -> TokenStream {
let proxied_field = ser_proxy_guard(&format!("self.{struct_fieldname}"), field);

if field.ty.base() == "Option" {
let proxy_attr = crate::shared::attrs_proxy(&field.attributes);
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();
}};
first_field_was_serialized = true;
s.field(d+1, \"{}\");", json_fieldname);
l!(
s,
"if let Some(t) = &{} {{ if first_field_was_serialized {{ s.conl(); }};first_field_was_serialized = true;s.field(d+1, \"{}\");t.ser_json(d+1, s);}};",
"{}
if let Some(t) = &{} {{
{}
t.ser_json(d+1, s);
}} {}",
if null_on_none { field_header } else { "" },
proxied_field,
json_fieldname
if null_on_none { "" } else { field_header },
if null_on_none {
"else {{
Option::<i32>::ser_json(&None, d+1, s);
}}"
} else {
""
}
);
} else {
l!(
s,
"if first_field_was_serialized {{ s.conl(); }};first_field_was_serialized = true;s.field(d+1,\"{}\"); {}.ser_json(d+1, s);",
"if first_field_was_serialized {{
s.conl();
}};
first_field_was_serialized = true;
s.field(d+1,\"{}\");
{}.ser_json(d+1, s);",
json_fieldname,
proxied_field
);
Expand Down
7 changes: 7 additions & 0 deletions derive/src/shared.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use alloc::{
format,

Check warning on line 2 in derive/src/shared.rs

View workflow job for this annotation

GitHub Actions / Test Individual Features (ron)

unused imports: `ToString`, `format`, and `vec::Vec`

Check warning on line 2 in derive/src/shared.rs

View workflow job for this annotation

GitHub Actions / Test Individual Features NoStd (ron)

unused imports: `ToString`, `format`, and `vec::Vec`
string::{String, ToString},
vec::Vec,
};
Expand Down Expand Up @@ -76,6 +76,13 @@
.any(|attr| attr.tokens.len() == 1 && attr.tokens[0] == "skip")
}

#[cfg(feature = "json")]
pub fn attrs_serialize_none_as_null(attributes: &[crate::parse::Attribute]) -> bool {
attributes
.iter()
.any(|attr| attr.tokens.len() == 1 && attr.tokens[0] == "serialize_none_as_null")
}

#[cfg(any(feature = "binary", feature = "json"))]
pub(crate) fn struct_bounds_strings(struct_: &Struct, bound_name: &str) -> (String, String) {
let generics: &Vec<_> = &struct_.generics;
Expand Down
32 changes: 32 additions & 0 deletions tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,38 @@ fn de_field_default() {
assert_eq!(test.foo2.x, 3);
}

#[test]
fn ser_none_as_null() {
#[derive(SerJson)]
struct Foo {
x: Option<i32>,
}

let a = Foo { x: None };
assert_eq!(SerJson::serialize_json(&a), r#"{}"#);

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

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]
fn de_ser_field_skip() {
#[derive(DeJson, SerJson)]
Expand Down
Loading