v2 / vlib / x / json2 / tests / decode_custom_test.v
98 lines · 81 sloc · 2.5 KB · 2d33a7f2819dd5fc1f4aa3b3ca0bcc660810d7af
Raw
1import x.json2 as json
2import math.big
3
4struct MyString implements json.StringDecoder, json.NumberDecoder, json.BooleanDecoder, json.NullDecoder {
5mut:
6 data string
7}
8
9pub fn (mut ms MyString) from_json_string(raw_string string) ! {
10 ms.data = raw_string
11}
12
13pub fn (mut ms MyString) from_json_number(raw_number string) ! {
14 mut first := true
15
16 for digit in raw_number {
17 if first {
18 first = false
19 } else {
20 ms.data += '-'
21 }
22
23 ms.data += match digit {
24 `-` { 'minus' }
25 `.` { 'dot' }
26 `e`, `E` { 'e' }
27 `0` { 'zero' }
28 `1` { 'one' }
29 `2` { 'two' }
30 `3` { 'three' }
31 `4` { 'four' }
32 `5` { 'five' }
33 `6` { 'six' }
34 `7` { 'seven' }
35 `8` { 'eight' }
36 `9` { 'nine' }
37 else { 'none' }
38 }
39 }
40}
41
42pub fn (mut ms MyString) from_json_boolean(boolean_value bool) {
43 ms.data = if boolean_value { 'yes' } else { 'no' }
44}
45
46pub fn (mut ms MyString) from_json_null() {
47 ms.data = 'default value'
48}
49
50struct NoCustom {
51 a int
52 b string
53}
54
55type MyString2 = string
56
57pub fn (mut ms MyString2) from_json_string(raw_string string) ! {
58 ms = raw_string.replace('-', '')
59}
60
61fn test_custom() {
62 assert json.decode[NoCustom]('{"a": 99, "b": "hi"}')! == NoCustom{
63 a: 99
64 b: 'hi'
65 }
66
67 assert json.decode[[]MyString]('["hi", -9.8e7, true, null]')! == [
68 MyString{
69 data: 'hi'
70 },
71 MyString{
72 data: 'minus-nine-dot-eight-e-seven'
73 },
74 MyString{
75 data: 'yes'
76 },
77 MyString{
78 data: 'default value'
79 },
80 ]
81}
82
83fn test_null() {
84 assert json.decode[json.Any]('null]')! == json.Any(json.null)
85 assert json.decode[json.Any]('{"hi": 90, "bye": ["lol", -1, null]}')!.str() == '{"hi":90,"bye":["lol",-1,null]}'
86}
87
88fn test_big() {
89 assert json.decode[big.Integer]('0')!.str() == '0'
90
91 assert json.decode[big.Integer]('12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890')!.str() == '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
92
93 assert json.decode[big.Integer]('-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890')!.str() == '-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
94}
95
96fn test_alias() {
97 assert json.decode[MyString2]('"h-e---l-lo"')! == 'hello'
98}
99