Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
json: fix json decode/encode with option type (#17393)
- Loading branch information
Showing
2 changed files
with
125 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import json | ||
|
||
pub struct MyStruct { | ||
pub mut: | ||
valuea int | ||
} | ||
|
||
pub struct MyStruct2 { | ||
pub mut: | ||
valuea int | ||
valueb ?MyStruct | ||
} | ||
|
||
struct Node { | ||
location NodeLocation [json: 'loc'] | ||
} | ||
|
||
struct NodeLocation { | ||
source_file ?SourceFile [json: 'includedFrom'] | ||
} | ||
|
||
struct SourceFile { | ||
path string [json: 'file'] | ||
} | ||
|
||
fn test_encode_decode() { | ||
assert json.encode(MyStruct2{ valuea: 1 }) == '{"valuea":1}' | ||
|
||
assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{ | ||
valuea: 1 | ||
valueb: none | ||
} | ||
} | ||
|
||
fn test_encode_decode2() { | ||
assert json.encode(MyStruct2{ valuea: 1, valueb: none }) == '{"valuea":1}' | ||
|
||
assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{ | ||
valuea: 1 | ||
valueb: none | ||
} | ||
} | ||
|
||
fn test_encode_decode3() { | ||
assert json.encode(MyStruct2{ | ||
valuea: 1 | ||
valueb: MyStruct{ | ||
valuea: 123 | ||
} | ||
}) == '{"valuea":1,"valueb":{"valuea":123}}' | ||
|
||
assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{ | ||
valuea: 1 | ||
valueb: none | ||
} | ||
} | ||
|
||
fn test_main() { | ||
node := json.decode(Node, '{"loc": { "includedFrom": { "file": "/bin/foo" } } }')! | ||
|
||
source_file := node.location.source_file or { | ||
SourceFile{ | ||
path: '-' | ||
} | ||
} | ||
|
||
assert source_file.path == '/bin/foo' | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters