Skip to content

Commit

Permalink
json: fix decode struct ptr (#20828)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Feb 15, 2024
1 parent 9aeb822 commit 4f742ad
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
22 changes: 22 additions & 0 deletions 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
}
9 changes: 8 additions & 1 deletion vlib/v/gen/c/json.v
Expand Up @@ -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()
}
}
Expand Down

0 comments on commit 4f742ad

Please sign in to comment.