diff --git a/vlib/json/json_struct_option_test.v b/vlib/json/json_struct_option_test.v new file mode 100644 index 0000000000..985e5b86d8 --- /dev/null +++ b/vlib/json/json_struct_option_test.v @@ -0,0 +1,46 @@ +import json + +pub struct MyStruct[T] { +pub mut: + result ?T + id string +} + +fn test_gn_struct_string() ! { + a := MyStruct[string]{ + result: 'test' + id: 'some id' + } + + encoded_string := json.encode(a) + dump(encoded_string) + test := json.decode(MyStruct[string], encoded_string)! + dump(test) + assert a == test +} + +fn test_gn_struct_int() ! { + a := MyStruct[int]{ + result: 1 + id: 'some id' + } + + encoded_string := json.encode(a) + dump(encoded_string) + test := json.decode(MyStruct[int], encoded_string)! + dump(test) + assert a == test +} + +fn test_gn_struct_f64() ! { + a := MyStruct[f64]{ + result: 1.2 + id: 'some id' + } + + encoded_string := json.encode(a) + dump(encoded_string) + test := json.decode(MyStruct[f64], encoded_string)! + dump(test) + assert a == test +} diff --git a/vlib/v/gen/c/json.v b/vlib/v/gen/c/json.v index b5d6e34641..96b6007765 100644 --- a/vlib/v/gen/c/json.v +++ b/vlib/v/gen/c/json.v @@ -164,7 +164,8 @@ ${enc_fn_dec} { g.gen_sumtype_enc_dec(utyp, sym, mut enc, mut dec, ret_styp) } else if sym.kind == .enum_ { g.gen_enum_enc_dec(utyp, sym, mut enc, mut dec) - } else if utyp.has_flag(.option) && sym.info !is ast.Struct { + } else if utyp.has_flag(.option) + && (is_js_prim(g.typ(utyp.clear_flag(.option))) || sym.info !is ast.Struct) { g.gen_option_enc_dec(utyp, mut enc, mut dec) } else { enc.writeln('\to = cJSON_CreateObject();')