v2 / vlib / x / json2 / custom.v
64 lines · 54 sloc · 1.9 KB · 3ffc951cf555dc4818309a507ccb9d0da4de748f
Raw
1module json2
2
3// implements encoding json, this is not validated so implementations must be correct
4pub interface JsonEncoder {
5 // to_json returns a string containing an objects json representation
6 to_json() string
7}
8
9// Encodable is an interface, that allows custom implementations for encoding structs to their string based JSON representations.
10
11@[deprecated: 'use `to_json` to implement `JsonEncoder` instead']
12@[deprecated_after: '2025-10-30']
13pub interface Encodable {
14 json_str() string
15}
16
17// implements decoding json strings, e.g. "hello, \u2164!"
18pub interface StringDecoder {
19mut:
20 // called with raw string (minus apostrophes) e.g. 'hello, \u2164!'
21 from_json_string(raw_string string) !
22}
23
24// implements decoding json numbers, e.g. -1.234e23
25pub interface NumberDecoder {
26mut:
27 // called with raw string of number e.g. '-1.234e23'
28 from_json_number(raw_number string) !
29}
30
31// implements decoding json true/false
32pub interface BooleanDecoder {
33mut:
34 // called with converted bool
35 // already checked so no error needed
36 from_json_boolean(boolean_value bool)
37}
38
39// implements decoding json null
40pub interface NullDecoder {
41mut:
42 // only has one value
43 // already checked so no error needed
44 from_json_null()
45}
46
47// Implement once generic interfaces are more stable
48
49// // implements decoding json arrays, e.g. ["hi", "bye", 0.9, true]
50// // elements are already decoded
51// pub interface ArrayDecoder[T] {
52// mut:
53// // called for every element in array e.g. 'hi', 'bye', '0.9', 'true'
54// from_json_value(raw_value T)!
55// }
56
57// // implements decoding json object, e.g. {"name": "foo", "name": "bar", "age": 99}
58// // this allows for duplicate/ordered keys to be decoded
59// // elements are already decoded
60// pub interface ObjectDecoder[T] {
61// mut:
62// // called for every key-value pair in object (minus apostrophes for keys) e.g. ('name': 'foo'), ('name': 'bar'), ('age': '99')
63// from_json_pair(raw_key string, raw_value T)!
64// }
65