1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

json2: refactor after #16951 (#16976)

This commit is contained in:
Hitalo Souza 2023-01-14 16:30:29 -03:00 committed by GitHub
parent dbfb9c3a90
commit 199db81b23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 17 deletions

View File

@ -14,6 +14,7 @@ const fixed_time = time.Time{
type StringAlias = string
type BoolAlias = bool
type IntAlias = int
type TimeAlias = time.Time
type StructAlias = StructType[int]
type SumTypes = bool | int | string
@ -205,6 +206,9 @@ fn test_alias() {
assert json.encode(StructType[IntAlias]{ val: 0 }) == '{"val":0}'
assert json.encode(StructType[IntAlias]{ val: 1 }) == '{"val":1}'
assert json.encode(StructType[TimeAlias]{}) == '{"val":"0000-00-00T00:00:00.000Z"}'
assert json.encode(StructType[TimeAlias]{ val: fixed_time }) == '{"val":"2022-03-11T13:54:25.000Z"}'
assert json.encode(StructType[StructAlias]{}) == '{"val":{"val":0}}'
assert json.encode(StructType[StructAlias]{ val: StructType[int]{0} }) == '{"val":{"val":0}}'
assert json.encode(StructType[StructAlias]{ val: StructType[int]{1} }) == '{"val":{"val":1}}'

View File

@ -259,23 +259,25 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
} $else $if field.is_enum {
wr.write(int(val.$(field.name)).str().bytes())!
} $else $if field.is_alias {
match field.unaliased_typ {
typeof[string]().idx {
$if field.unaliased_typ is string {
e.encode_string(value.str(), mut wr)!
}
typeof[bool]().idx, typeof[f32]().idx, typeof[f64]().idx, typeof[i8]().idx,
typeof[i16]().idx, typeof[int]().idx, typeof[i64]().idx, typeof[u8]().idx,
typeof[u16]().idx, typeof[u32]().idx, typeof[u64]().idx {
} $else $if field.unaliased_typ is time.Time {
parsed_time := val.$(field.name) as time.Time
e.encode_string(parsed_time.format_rfc3339(), mut wr)!
} $else $if field.unaliased_typ in [bool, $Float, $Int] {
wr.write(value.str().bytes())!
}
typeof[[]byte]().idx, typeof[[]int]().idx {
// FIXME - error: could not infer generic type `U` in call to `encode_array`
// e.encode_array(value, level, mut wr)!
}
else {
// FIXME
// $else $if field.unaliased_typ is $Array {
// // e.encode_array(value, level + 1, mut wr)!
// } $else $if field.unaliased_typ is $Struct {
// // e.encode_struct(value, level + 1, mut wr)!
// } $else $if field.unaliased_typ is $Enum {
// // wr.write(int(val.$(field.name)).str().bytes())!
// }
$else {
e.encode_struct(value, level + 1, mut wr)!
// e.encode_value_with_level(value, level + 1, mut wr)!
}
// return error('the alias ${typeof(val).name} cannot be encoded')
}
} $else {
return error('type ${typeof(val).name} cannot be array encoded')