| 1 | import json |
| 2 | |
| 3 | struct Result[T] { |
| 4 | ok bool |
| 5 | result T |
| 6 | } |
| 7 | |
| 8 | struct User { |
| 9 | id int |
| 10 | username string |
| 11 | } |
| 12 | |
| 13 | struct Box[T] { |
| 14 | items []T |
| 15 | } |
| 16 | |
| 17 | fn func[T]() !T { |
| 18 | text := '{"ok": true, "result":{"id":37467243, "username": "ciao"}}' |
| 19 | a := json.decode(Result[T], text)! |
| 20 | return a.result |
| 21 | } |
| 22 | |
| 23 | fn string_decode[T](text string) !T { |
| 24 | return json.decode(T, text) |
| 25 | } |
| 26 | |
| 27 | fn open_box[T](text string) ![]T { |
| 28 | box := string_decode[Box[T]](text)! |
| 29 | return box.items |
| 30 | } |
| 31 | |
| 32 | fn test_decode_with_generic_struct() { |
| 33 | ret := func[User]()! |
| 34 | println(ret) |
| 35 | assert ret.id == 37467243 |
| 36 | assert ret.username == 'ciao' |
| 37 | } |
| 38 | |
| 39 | fn test_decode_with_nested_generic_struct() { |
| 40 | text := '{"items":[{},{"id":37467243,"username":"ciao"},{}]}' |
| 41 | items := open_box[User](text)! |
| 42 | assert items.len == 3 |
| 43 | assert items[0].id == 0 |
| 44 | assert items[0].username == '' |
| 45 | assert items[1].id == 37467243 |
| 46 | assert items[1].username == 'ciao' |
| 47 | assert items[2].id == 0 |
| 48 | assert items[2].username == '' |
| 49 | } |
| 50 | |