v2 / vlib / v / tests / comptime / comptime_map_generic_test.v
47 lines · 41 sloc · 932 bytes · 2d33a7f2819dd5fc1f4aa3b3ca0bcc660810d7af
Raw
1import x.json2
2
3struct User {
4pub mut:
5 numbers map[string]string
6}
7
8fn test_main() {
9 user_json := '{"numbers":{"home":"123456","work":"987653"}}'
10 res := json2.decode[json2.Any](user_json)!.as_map()
11
12 mut numbers := map[string]string{}
13 decode_map(mut numbers, res['numbers']!.as_map())!
14 assert numbers == {
15 'home': '123456'
16 'work': '987653'
17 }
18
19 assert decode_struct[User](res)! == User{
20 numbers: {
21 'home': '123456'
22 'work': '987653'
23 }
24 }
25}
26
27fn decode_struct[T](res map[string]json2.Any) !T {
28 mut typ := T{}
29 $for field in T.fields {
30 $if field.is_map {
31 decode_map(mut typ.$(field.name), res[field.name]!.as_map())!
32 } $else {
33 return error("The type of `${field.name}` can't be decoded.")
34 }
35 }
36 return typ
37}
38
39fn decode_map[V](mut m map[string]V, res map[string]json2.Any) ! {
40 $if V is $string {
41 for k, v in res {
42 m[k] = v.str()
43 }
44 } $else {
45 return error("The map value can't be decoded.")
46 }
47}
48