Created
July 15, 2021 17:54
-
-
Save spytheman/86f0dd20ccf89ad6f0908fb7b634d3a3 to your computer and use it in GitHub Desktop.
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
import x.json2 | |
struct First { | |
mut: | |
a int | |
} | |
struct Second { | |
mut: | |
ok bool | |
} | |
type ZType = First | Second | |
struct MyS { | |
mut: | |
s string | |
c ZType | |
} | |
////// | |
pub fn (z ZType) to_any() json2.Any { | |
mut mc := map[string]json2.Any{} | |
mc['kind'] = typeof(z) | |
mc['value'] = match z { | |
First { | |
json2.Any(map{ | |
'a': json2.Any(z.a) | |
}) | |
} | |
Second { | |
json2.Any(map{ | |
'ok': json2.Any(z.ok) | |
}) | |
} | |
} | |
return mc | |
} | |
pub fn (s MyS) to_json() string { | |
mut mp := map[string]json2.Any{} | |
mp['s'] = s.s | |
mp['c'] = s.c.to_any() | |
return mp.str() | |
} | |
pub fn (mut s MyS) from_json(f json2.Any) { | |
mp := f.as_map() | |
s.s = mp['s'].str() | |
mc := mp['c'].as_map() | |
value := mc['value'].as_map() | |
kind := mc['kind'].str() | |
match kind { | |
'First' { | |
s.c = First{ | |
a: value['a'].int() | |
} | |
} | |
'Second' { | |
s.c = Second{ | |
ok: value['ok'].bool() | |
} | |
} | |
else { | |
eprintln('unknown kind: $kind') | |
} | |
} | |
} | |
fn encode_decode(original MyS) ? { | |
println('Original: $original') | |
s := json2.encode(original) | |
println('=> Serialised as json: $s') | |
result := json2.decode<MyS>(s) ? | |
println('Read back from json: $result') | |
} | |
fn main() { | |
encode_decode(MyS{ | |
s: 'name' | |
c: ZType(First{1}) | |
}) ? | |
eprintln('-'.repeat(80)) | |
encode_decode(MyS{ | |
s: 'name' | |
c: ZType(Second{ | |
ok: true | |
}) | |
}) ? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Produces: