From bd22d58f376dde8d6f0fd6c1f5c4d0b3b02c9c29 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 21 Sep 2024 19:40:18 -0300 Subject: [PATCH] fix --- vlib/json/json_encode_embed_test.v | 27 +++++++++++++++++++++++++++ vlib/v/gen/c/json.v | 11 ++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 vlib/json/json_encode_embed_test.v diff --git a/vlib/json/json_encode_embed_test.v b/vlib/json/json_encode_embed_test.v new file mode 100644 index 00000000000000..085c5815bfaea4 --- /dev/null +++ b/vlib/json/json_encode_embed_test.v @@ -0,0 +1,27 @@ +import json + +struct Json2 { + inner []f64 +} + +struct Json { + Json2 + test f64 +} + +fn test_main() { + str := '{"inner":[1,2,3,4,5],"test":1.2}' + data := json.decode(Json, str) or { + eprintln('Failed to decode json, error: ${err}') + return + } + println(data) + assert data.inner.len == 5 + assert data.inner[0] == 1.0 + assert data.inner[4] == 5.0 + assert data.test == 1.2 + + data_json := json.encode(data) + dump(data_json) + assert data_json == str +} diff --git a/vlib/v/gen/c/json.v b/vlib/v/gen/c/json.v index 4bbfc783bf39c0..a706a7faea3ce4 100644 --- a/vlib/v/gen/c/json.v +++ b/vlib/v/gen/c/json.v @@ -614,6 +614,7 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st mut is_skip := false mut is_required := false mut is_omit_empty := false + mut skip_embed := false for attr in field.attrs { match attr.name { @@ -768,10 +769,10 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st if embed == int(field.typ) { g.gen_struct_enc_dec(field.typ, g.table.sym(field.typ).info, styp, mut enc, mut dec, name) + skip_embed = true break } } - continue } tmp := g.new_tmp_var() gen_js_get_opt(dec_name, field_type, styp, tmp, name, mut dec, is_required) @@ -797,15 +798,15 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st dec.writeln('\t}') } } - if embed_prefix.len > 0 { - return + if skip_embed { + continue } // Encoding mut enc_name := js_enc_name(field_type) prefix_enc := if utyp.has_flag(.option) { - '(*(${g.base_type(utyp)}*)val.data)' + '(*(${g.base_type(utyp)}*)val${embed_member}.data)' } else { - 'val' + 'val${embed_member}' } is_option := field.typ.has_flag(.option) indent := if is_option { '\t\t' } else { '\t' }