v2 / vlib / json / tests / json_decode_with_generic_test.v
49 lines · 41 sloc · 927 bytes · 30b8d0091c9b9e571f3324e128ba32567c2fdbf5
Raw
1import json
2
3struct Result[T] {
4 ok bool
5 result T
6}
7
8struct User {
9 id int
10 username string
11}
12
13struct Box[T] {
14 items []T
15}
16
17fn 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
23fn string_decode[T](text string) !T {
24 return json.decode(T, text)
25}
26
27fn open_box[T](text string) ![]T {
28 box := string_decode[Box[T]](text)!
29 return box.items
30}
31
32fn test_decode_with_generic_struct() {
33 ret := func[User]()!
34 println(ret)
35 assert ret.id == 37467243
36 assert ret.username == 'ciao'
37}
38
39fn 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