| 1 | module json2 |
| 2 | |
| 3 | // implements encoding json, this is not validated so implementations must be correct |
| 4 | pub 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'] |
| 13 | pub interface Encodable { |
| 14 | json_str() string |
| 15 | } |
| 16 | |
| 17 | // implements decoding json strings, e.g. "hello, \u2164!" |
| 18 | pub interface StringDecoder { |
| 19 | mut: |
| 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 |
| 25 | pub interface NumberDecoder { |
| 26 | mut: |
| 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 |
| 32 | pub interface BooleanDecoder { |
| 33 | mut: |
| 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 |
| 40 | pub interface NullDecoder { |
| 41 | mut: |
| 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 | |