Skip to content

Commit 511274a

Browse files
authored
json: fix raw decode to option string of complex data (#18902)
1 parent a49b8f2 commit 511274a

2 files changed

Lines changed: 63 additions & 1 deletion

File tree

vlib/json/json_option_raw_test.v

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import json
2+
3+
pub struct Dto {
4+
pub:
5+
key string [raw]
6+
key2 string [raw]
7+
data ?string [raw]
8+
optional ?string [raw]
9+
}
10+
11+
fn test_main() {
12+
raw_json := '{
13+
"key": [1, 2, "test"],
14+
"key2": { "test": 1 },
15+
"data": { "test": 1 },
16+
"optional": "test"
17+
}'
18+
19+
dto := json.decode(Dto, raw_json)!
20+
21+
println(dto)
22+
assert dto.data? == '{"test":1}'
23+
}
24+
25+
fn test_none() {
26+
raw_json := '{
27+
"key": [1, 2, "test"],
28+
"optional": "test"
29+
}'
30+
31+
dto := json.decode(Dto, raw_json)!
32+
33+
println(dto)
34+
assert dto.data == none
35+
assert dto.optional? == '"test"'
36+
}
37+
38+
fn test_null() {
39+
raw_json := '{
40+
"key": [1, 2, "test"],
41+
"key2": null,
42+
"data": null,
43+
"optional": "test"
44+
}'
45+
46+
dto := json.decode(Dto, raw_json)!
47+
48+
println(dto)
49+
assert dto.key2 == 'null'
50+
assert dto.data? == 'null'
51+
}
52+
53+
fn test_not_set() {
54+
raw_json := '{
55+
}'
56+
57+
dto := json.decode(Dto, raw_json)!
58+
59+
println(dto)
60+
assert dto.data == none
61+
assert dto.optional == none
62+
}

vlib/v/gen/c/json.v

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,7 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
629629
if field.typ.has_flag(.option) {
630630
g.gen_json_for_type(field.typ)
631631
base_typ := g.base_type(field.typ)
632-
dec.writeln('\tif (!cJSON_IsString(js_get(root, "${name}")))')
632+
dec.writeln('\tif (js_get(root, "${name}") == NULL)')
633633
dec.writeln('\t\t_option_none(&(${base_typ}[]) { {0} }, &${prefix}${op}${c_name(field.name)}, sizeof(${base_typ}));')
634634
dec.writeln('\telse')
635635
dec.writeln('\t\t_option_ok(&(${base_typ}[]) { tos5(cJSON_PrintUnformatted(js_get(root, "${name}"))) }, &${prefix}${op}${c_name(field.name)}, sizeof(${base_typ}));')

0 commit comments

Comments
 (0)