diff --git a/vlib/json/json_test.v b/vlib/json/json_test.v index 1caffaf640..cb22c97589 100644 --- a/vlib/json/json_test.v +++ b/vlib/json/json_test.v @@ -49,11 +49,11 @@ fn test_parse_user() { assert u.typ == 1 } -/* fn test_encode_user(){ usr := User{ age: 10, nums: [1,2,3], last_name: 'Johnson', is_registered: true, typ: 0} expected := '{"age":10,"nums":[1,2,3],"lastName":"Johnson","IsRegistered":true,"type":0}' out := json.encode(usr) + println(out) assert out == expected } @@ -70,4 +70,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 a224d4085f..13db15c1c0 100644 --- a/vlib/v/gen/json.v +++ b/vlib/v/gen/json.v @@ -61,6 +61,7 @@ cJSON* ${enc_fn_name}($styp val) { value_type := g.table.value_type(typ) g.gen_json_for_type(value_type) dec.writeln(g.decode_array(value_type)) + enc.writeln(g.encode_array(value_type)) // enc += g.encode_array(t) } else { // Structs. Range through fields @@ -76,7 +77,7 @@ cJSON* ${enc_fn_name}($styp val) { field_type := g.typ(field.typ) enc_name := js_enc_name(field_type) if field.attr == 'raw' { - dec.writeln(' res->$field.name = tos2(cJSON_PrintUnformatted(' + 'js_get(root, "$name")));') + dec.writeln(' res . $field.name = tos2(cJSON_PrintUnformatted(' + 'js_get(root, "$name")));') } else { // Now generate decoders for all field types in this struct // need to do it here so that these functions are generated first @@ -136,3 +137,14 @@ $s } ' } + +fn (mut g Gen) encode_array(value_type table.Type) string { + styp := g.typ(value_type) + fn_name := js_enc_name(styp) + return ' +o = cJSON_CreateArray(); +for (int i = 0; i < val.len; i++){ + cJSON_AddItemToArray(o, $fn_name ( (($styp*)val.data)[i] )); +} +' +}