v / vlib / json / tests / json_decode_struct_ptr_test.v
42 lines · 35 sloc · 1.07 KB · 21e8cf56c8fdbc71d752b75857964f26570547a0
Raw
1import json
2
3struct Message {
4mut:
5 id int
6 text string
7 reply_to &Message
8}
9
10struct OptionalMessage {
11mut:
12 id int
13 text string
14 reply_to ?&OptionalMessage
15}
16
17fn 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
31fn 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