| 1 | import json |
| 2 | |
| 3 | struct Message { |
| 4 | mut: |
| 5 | id int |
| 6 | text string |
| 7 | reply_to &Message |
| 8 | } |
| 9 | |
| 10 | struct OptionalMessage { |
| 11 | mut: |
| 12 | id int |
| 13 | text string |
| 14 | reply_to ?&OptionalMessage |
| 15 | } |
| 16 | |
| 17 | fn test_main() { |
| 18 | mut json_data := '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi"}}' |
| 19 | mut message := json.decode(Message, json_data)! |
| 20 | assert message.reply_to.id == 2 |
| 21 | |
| 22 | json_data = '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi", "reply_to": {}}}' |
| 23 | message = json.decode(Message, json_data)! |
| 24 | assert message.reply_to.reply_to.reply_to == unsafe { nil } |
| 25 | |
| 26 | json_data = '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi", "reply_to": {"id": 5}}}' |
| 27 | message = json.decode(Message, json_data)! |
| 28 | assert message.reply_to.reply_to.id == 5 |
| 29 | } |
| 30 | |
| 31 | fn test_recursive_optional_struct_ptr() { |
| 32 | json_data := '{"id": 1, "text": "Hello", "reply_to": {"id": 2, "text": "Hi", "reply_to": null}}' |
| 33 | message := json.decode(OptionalMessage, json_data)! |
| 34 | reply := message.reply_to or { |
| 35 | assert false |
| 36 | return |
| 37 | } |
| 38 | |
| 39 | assert reply.id == 2 |
| 40 | assert reply.text == 'Hi' |
| 41 | assert reply.reply_to == none |
| 42 | } |
| 43 | |