Skip to content

Commit 75deb66

Browse files
authored
json: fix decode option string (#17812)
1 parent dd0b68a commit 75deb66

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

vlib/json/json_struct_option_test.v

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import json
2+
3+
pub struct MyStruct[T] {
4+
pub mut:
5+
result ?T
6+
id string
7+
}
8+
9+
fn test_gn_struct_string() ! {
10+
a := MyStruct[string]{
11+
result: 'test'
12+
id: 'some id'
13+
}
14+
15+
encoded_string := json.encode(a)
16+
dump(encoded_string)
17+
test := json.decode(MyStruct[string], encoded_string)!
18+
dump(test)
19+
assert a == test
20+
}
21+
22+
fn test_gn_struct_int() ! {
23+
a := MyStruct[int]{
24+
result: 1
25+
id: 'some id'
26+
}
27+
28+
encoded_string := json.encode(a)
29+
dump(encoded_string)
30+
test := json.decode(MyStruct[int], encoded_string)!
31+
dump(test)
32+
assert a == test
33+
}
34+
35+
fn test_gn_struct_f64() ! {
36+
a := MyStruct[f64]{
37+
result: 1.2
38+
id: 'some id'
39+
}
40+
41+
encoded_string := json.encode(a)
42+
dump(encoded_string)
43+
test := json.decode(MyStruct[f64], encoded_string)!
44+
dump(test)
45+
assert a == test
46+
}

vlib/v/gen/c/json.v

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,8 @@ ${enc_fn_dec} {
164164
g.gen_sumtype_enc_dec(utyp, sym, mut enc, mut dec, ret_styp)
165165
} else if sym.kind == .enum_ {
166166
g.gen_enum_enc_dec(utyp, sym, mut enc, mut dec)
167-
} else if utyp.has_flag(.option) && sym.info !is ast.Struct {
167+
} else if utyp.has_flag(.option)
168+
&& (is_js_prim(g.typ(utyp.clear_flag(.option))) || sym.info !is ast.Struct) {
168169
g.gen_option_enc_dec(utyp, mut enc, mut dec)
169170
} else {
170171
enc.writeln('\to = cJSON_CreateObject();')

0 commit comments

Comments
 (0)