From 4f742ad1b2f0b4a049c26d2683a516b90496464a Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Thu, 15 Feb 2024 01:41:10 -0300 Subject: [PATCH] json: fix decode struct ptr (#20828) --- vlib/json/json_decode_struct_ptr_test.v | 22 ++++++++++++++++++++++ vlib/v/gen/c/json.v | 9 ++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 vlib/json/json_decode_struct_ptr_test.v diff --git a/vlib/json/json_decode_struct_ptr_test.v b/vlib/json/json_decode_struct_ptr_test.v new file mode 100644 index 00000000000000..954d025c2717e8 --- /dev/null +++ b/vlib/json/json_decode_struct_ptr_test.v @@ -0,0 +1,22 @@ +import json + +struct Message { +mut: + id int + text string + reply_to &Message +} + +fn test_main() { + mut json_data := '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi"}}' + mut message := json.decode(Message, json_data)! + assert message.reply_to.id == 2 + + json_data = '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi", "reply_to": {}}}' + message = json.decode(Message, json_data)! + assert message.reply_to.reply_to.reply_to == unsafe { nil } + + json_data = '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi", "reply_to": {"id": 5}}}' + message = json.decode(Message, json_data)! + assert message.reply_to.reply_to.id == 5 +} diff --git a/vlib/v/gen/c/json.v b/vlib/v/gen/c/json.v index 13d647c0704958..9c0b94a89ca76d 100644 --- a/vlib/v/gen/c/json.v +++ b/vlib/v/gen/c/json.v @@ -75,10 +75,17 @@ fn (mut g Gen) gen_jsons() { g.set_current_pos_as_last_stmt_pos() pos := g.out.len g.write(init_styp) + if utyp.is_ptr() { + ptr_styp := g.typ(utyp.set_nr_muls(utyp.nr_muls() - 1)) + g.write('HEAP(${ptr_styp}, ') + } g.expr(ast.Expr(ast.StructInit{ - typ: utyp + typ: utyp.set_nr_muls(0) typ_str: styp })) + if utyp.is_ptr() { + g.write(')') + } init_styp = g.out.cut_to(pos).trim_space() } }