diff --git a/cmd/tools/vtest-fixed.v b/cmd/tools/vtest-fixed.v index 815bbc7670..af7469f341 100644 --- a/cmd/tools/vtest-fixed.v +++ b/cmd/tools/vtest-fixed.v @@ -7,7 +7,6 @@ import v.pref const ( skip_test_files = [ 'vlib/arrays/arrays_test.v', - 'vlib/json/json_test.v', 'vlib/v/tests/enum_bitfield_test.v', 'vlib/v/tests/num_lit_call_method_test.v', 'vlib/v/tests/pointers_test.v', diff --git a/vlib/json/json_test.v b/vlib/json/json_test.v index 7fc0308601..21c7f04b25 100644 --- a/vlib/json/json_test.v +++ b/vlib/json/json_test.v @@ -1,5 +1,22 @@ import json +struct Employee { + name string + age int +} + +fn test_simple() { + x := Employee{'Peter', 28} + s := json.encode(x) + assert s == '{"name":"Peter","age":28}' + y := json.decode(Employee, s) or { + assert false + } + assert y.name == 'Peter' + assert y.age == 28 +} + +/* struct User { age int nums []int @@ -43,3 +60,4 @@ fn test_raw_json_field() { assert color.point == '{"Y":123}' assert color.space == 'YCbCr' } +*/ diff --git a/vlib/v/gen/json.v b/vlib/v/gen/json.v index f0d5feff23..79f50a97ac 100644 --- a/vlib/v/gen/json.v +++ b/vlib/v/gen/json.v @@ -25,6 +25,9 @@ fn (mut g Gen) gen_json_for_type(typ table.Type) { if sym.name in ['int', 'string', 'bool'] { return } + if sym.kind == .array { + return + } // println('gen_json_for_type($typ.name)') // decode_TYPE funcs receive an actual cJSON* object to decode // cJSON_Parse(str) call is added by the compiler @@ -55,6 +58,9 @@ cJSON* ${enc_fn_name}($styp val) { // enc += p.encode_array(t) } // Range through fields + if !(sym.info is table.Struct) { + verror('json: $sym.name is not struct') + } info := sym.info as table.Struct for field in info.fields { if field.attr == 'skip' { @@ -71,11 +77,10 @@ cJSON* ${enc_fn_name}($styp val) { g.gen_json_for_type(field.typ) dec_name := js_dec_name(field_type) if is_js_prim(field_type) { - dec.writeln(' res . $field.name = $dec_name (js_get(' + 'root, "$name"))') + dec.writeln(' res . $field.name = $dec_name (js_get(' + 'root, "$name"));') } else { - dec.writeln(' $dec_name (js_get(root, "$name"), & (res->$field.name))') + dec.writeln(' $dec_name (js_get(root, "$name"), & (res . $field.name));') } - dec.writeln(';') } enc.writeln('\tcJSON_AddItemToObject(o, "$name", ${enc_name}(val.$field.name));') }