| 1 | import json |
| 2 | |
| 3 | pub struct MyStruct { |
| 4 | pub mut: |
| 5 | valuea int |
| 6 | } |
| 7 | |
| 8 | pub struct MyStruct2 { |
| 9 | pub mut: |
| 10 | valuea int |
| 11 | valueb ?MyStruct |
| 12 | } |
| 13 | |
| 14 | struct Node { |
| 15 | location NodeLocation @[json: 'loc'] |
| 16 | } |
| 17 | |
| 18 | struct NodeLocation { |
| 19 | source_file ?SourceFile @[json: 'includedFrom'] |
| 20 | } |
| 21 | |
| 22 | struct SourceFile { |
| 23 | path string @[json: 'file'] |
| 24 | } |
| 25 | |
| 26 | fn test_encode_decode() { |
| 27 | assert json.encode(MyStruct2{ valuea: 1 }) == '{"valuea":1}' |
| 28 | |
| 29 | assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{ |
| 30 | valuea: 1 |
| 31 | valueb: none |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | fn test_encode_decode2() { |
| 36 | assert json.encode(MyStruct2{ valuea: 1, valueb: none }) == '{"valuea":1}' |
| 37 | |
| 38 | assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{ |
| 39 | valuea: 1 |
| 40 | valueb: none |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn test_encode_decode3() { |
| 45 | assert json.encode(MyStruct2{ |
| 46 | valuea: 1 |
| 47 | valueb: MyStruct{ |
| 48 | valuea: 123 |
| 49 | } |
| 50 | }) == '{"valuea":1,"valueb":{"valuea":123}}' |
| 51 | |
| 52 | assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{ |
| 53 | valuea: 1 |
| 54 | valueb: none |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn test_main() { |
| 59 | node := json.decode(Node, '{"loc": { "includedFrom": { "file": "/bin/foo" } } }')! |
| 60 | |
| 61 | source_file := node.location.source_file or { |
| 62 | SourceFile{ |
| 63 | path: '-' |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | assert source_file.path == '/bin/foo' |
| 68 | } |
| 69 | |