From 98f13ef491af19b932c15b16dfe10e6c3cdc565f Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 22 Dec 2024 19:26:55 -0300 Subject: [PATCH] json: fix codegen for struct default expr (fix #23216) (#23233) --- .../json_decode_struct_with_default_test.v | 34 +++++++++++++++++++ vlib/v/gen/c/json.v | 9 ++++- 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 vlib/json/tests/json_decode_struct_with_default_test.v diff --git a/vlib/json/tests/json_decode_struct_with_default_test.v b/vlib/json/tests/json_decode_struct_with_default_test.v new file mode 100644 index 000000000..2c242c69b --- /dev/null +++ b/vlib/json/tests/json_decode_struct_with_default_test.v @@ -0,0 +1,34 @@ +import json + +pub struct Response { +pub: + results []Result = []Result{len: 0} @[json: list] + tags []string = []string{len: 0} @[json: tags] + kind string @[json: result_type] +} + +pub struct Result { +pub: + id int @[json: defid] + author string @[json: author] + definition string @[json: definition] + link string @[json: permalink] + thumbs_down int @[json: thumbs_down] + thumbs_up int @[json: thumbs_up] + word string @[json: word] + date string @[json: written_on] + audio_samples []string @[json: sound_urls] + example string @[json: example] +} + +pub fn define(word string) !&Response { + resp := '{"list":[{"defid":3439287}]}' + response := json.decode(Response, resp) or { return err } + return &response +} + +fn test_main() { + response := define('')! + assert response.results.len > 0 + assert response.results[0].id == 3439287 +} diff --git a/vlib/v/gen/c/json.v b/vlib/v/gen/c/json.v index bac38923e..4faaa578c 100644 --- a/vlib/v/gen/c/json.v +++ b/vlib/v/gen/c/json.v @@ -850,7 +850,14 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st } if field.has_default_expr { dec.writeln('\t} else {') - dec.writeln('\t\t${prefix}${op}${c_name(field.name)} = ${g.expr_string(field.default_expr)};') + default_str := g.expr_string(field.default_expr) + lines := default_str.count('\n') + if lines > 1 { + dec.writeln(default_str.all_before_last('\n')) + dec.writeln('\t\t${prefix}${op}${c_name(field.name)} = ${default_str.all_after_last('\n')};') + } else { + dec.writeln('\t\t${prefix}${op}${c_name(field.name)} = ${default_str};') + } } dec.writeln('\t}') } -- 2.39.5