mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
json: allow decode/encode of alias to primitive type (#18003)
This commit is contained in:
parent
456968b07d
commit
488e14bf99
40
vlib/json/json_encode_primite_test.v
Normal file
40
vlib/json/json_encode_primite_test.v
Normal file
@ -0,0 +1,40 @@
|
||||
import json
|
||||
|
||||
struct Test {
|
||||
field MySumType
|
||||
}
|
||||
|
||||
type MyInt = int
|
||||
type MyString = string
|
||||
type MySumType = MyString | int | string
|
||||
|
||||
fn test_alias_to_primitive() {
|
||||
mut test := Test{
|
||||
field: MyString('foo')
|
||||
}
|
||||
mut encoded := json.encode(test)
|
||||
assert dump(encoded) == '{"field":"foo"}'
|
||||
assert json.decode(Test, '{"field": "foo"}')!.field == MySumType('foo')
|
||||
|
||||
test = Test{
|
||||
field: 'foo'
|
||||
}
|
||||
encoded = json.encode(test)
|
||||
assert dump(encoded) == '{"field":"foo"}'
|
||||
assert json.decode(Test, '{"field":"foo"}')! == test
|
||||
|
||||
test = Test{
|
||||
field: 1
|
||||
}
|
||||
encoded = json.encode(test)
|
||||
assert dump(encoded) == '{"field":1}'
|
||||
assert json.decode(Test, '{"field":1}')! == test
|
||||
|
||||
mut test2 := MyString('foo')
|
||||
encoded = json.encode(test2)
|
||||
assert dump(encoded) == '"foo"'
|
||||
|
||||
mut test3 := MyInt(1000)
|
||||
encoded = json.encode(test3)
|
||||
assert dump(encoded) == '1000'
|
||||
}
|
@ -143,9 +143,8 @@ ${enc_fn_dec} {
|
||||
psym := g.table.sym(parent_typ)
|
||||
if is_js_prim(g.typ(parent_typ)) {
|
||||
g.gen_json_for_type(parent_typ)
|
||||
continue
|
||||
}
|
||||
if psym.info is ast.Struct {
|
||||
g.gen_prim_enc_dec(parent_typ, mut enc, mut dec)
|
||||
} else if psym.info is ast.Struct {
|
||||
enc.writeln('\to = cJSON_CreateObject();')
|
||||
g.gen_struct_enc_dec(utyp, psym.info, ret_styp, mut enc, mut dec)
|
||||
} else if psym.kind == .enum_ {
|
||||
@ -261,6 +260,16 @@ fn (mut g Gen) gen_enum_enc_dec(utyp ast.Type, sym ast.TypeSymbol, mut enc strin
|
||||
}
|
||||
}
|
||||
|
||||
[inline]
|
||||
fn (mut g Gen) gen_prim_enc_dec(typ ast.Type, mut enc strings.Builder, mut dec strings.Builder) {
|
||||
type_str := g.typ(typ.clear_flag(.option))
|
||||
encode_name := js_enc_name(type_str)
|
||||
enc.writeln('\to = ${encode_name}(val);')
|
||||
|
||||
dec_name := js_dec_name(type_str)
|
||||
dec.writeln('\tres = ${dec_name}(root);')
|
||||
}
|
||||
|
||||
[inline]
|
||||
fn (mut g Gen) gen_option_enc_dec(typ ast.Type, mut enc strings.Builder, mut dec strings.Builder) {
|
||||
enc.writeln('\tif (val.state == 2) {')
|
||||
|
Loading…
Reference in New Issue
Block a user