Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Dec 30, 2024
1 parent d9f5112 commit f877f47
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
26 changes: 26 additions & 0 deletions vlib/json/tests/json_is_null_attr_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import json

struct Bar {
name ?string @[json_null]
}

struct Foo {
name ?string @[json_null]
age ?int @[json_null]
text ?string
other ?Bar
other2 ?Bar @[json_null]
}

fn test_main() {
assert json.encode(Foo{}) == '{"name":null,"age":null,"other2":null}'
assert json.encode(Foo{ name: '' }) == '{"name":"","age":null,"other2":null}'
assert json.encode(Foo{ age: 10 }) == '{"name":null,"age":10,"other2":null}'
assert json.encode(Foo{
age: 10
other2: Bar{
name: none
}
}) == '{"name":null,"age":10,"other2":{"name":null}}'
assert json.decode(Foo, json.encode(Foo{}))! == Foo{}
}
12 changes: 10 additions & 2 deletions vlib/v/gen/c/json.v
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ fn (mut g Gen) gen_prim_enc_dec(typ ast.Type, mut enc strings.Builder, mut dec s
@[inline]
fn (mut g Gen) gen_option_enc_dec(typ ast.Type, mut enc strings.Builder, mut dec strings.Builder) {
enc.writeln('\tif (val.state == 2) {')
enc.writeln('\t\treturn NULL;')
enc.writeln('\t\treturn cJSON_CreateNull();')
enc.writeln('\t}')
type_str := g.styp(typ.clear_flag(.option))
encode_name := js_enc_name(type_str)
Expand Down Expand Up @@ -649,6 +649,7 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
mut is_required := false
mut is_omit_empty := false
mut skip_embed := false
mut is_json_null := false

for attr in field.attrs {
match attr.name {
Expand All @@ -672,6 +673,9 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
'omitempty' {
is_omit_empty = true
}
'json_null' {
is_json_null = true
}
else {}
}
}
Expand Down Expand Up @@ -952,7 +956,11 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
}

if is_option {
enc.writeln('\t} // !none')
if is_json_null {
enc.writeln('\t} else {')
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", cJSON_CreateNull());')
}
enc.writeln('\t}')
}
}
}
Expand Down

0 comments on commit f877f47

Please sign in to comment.