1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: fix json encoding of structs with option fields (skip the fields with a value of none) (#16916)

This commit is contained in:
yuyi 2023-01-09 21:33:08 +08:00 committed by GitHub
parent 2ec6e2b209
commit 286350aa9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 5 deletions

View File

@ -1,4 +1,5 @@
import json
import x.json2
struct Foo {
name string
@ -11,10 +12,18 @@ fn test_json_encode_struct_with_option_field() {
}
ret1 := json.encode(f1)
println(ret1)
assert ret1 == '{"name":"hello","num":null}'
assert ret1 == '{"name":"hello"}'
ret2 := json2.encode(f1)
println(ret2)
assert ret2 == '{"name":"hello"}'
f2 := Foo{'hello', 22}
ret2 := json.encode(f2)
println(ret2)
assert ret2 == '{"name":"hello","num":22}'
ret3 := json.encode(f2)
println(ret3)
assert ret3 == '{"name":"hello","num":22}'
ret4 := json2.encode(f2)
println(ret4)
assert ret4 == '{"name":"hello","num":22}'
}

View File

@ -170,7 +170,7 @@ ${enc_fn_dec} {
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 cJSON_CreateNull();')
enc.writeln('\t\treturn NULL;')
enc.writeln('\t}')
type_str := g.typ(typ.clear_flag(.option))
encode_name := js_enc_name(type_str)