mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
x.json2: support time.Time values in encode (#16643)
* feat: json2 time.Time encode
* refactor: best var name
* fix: use 'RFC 3339' as pattern in json encode
* fix: unused var for unaliased_typ
* fix: improve test
* use the clearer test after V ad24c22
, that made format_rfc3339 more stable
Co-authored-by: Delyan Angelov <delian66@gmail.com>
This commit is contained in:
@ -5,6 +5,7 @@ module json2
|
||||
|
||||
import io
|
||||
import strings
|
||||
import time
|
||||
|
||||
// Encoder encodes the an `Any` type into JSON representation.
|
||||
// It provides parameters in order to change the end result.
|
||||
@ -112,6 +113,7 @@ fn (e &Encoder) encode_any(val Any, level int, mut wr io.Writer) ! {
|
||||
e.encode_newline(level - 1, mut wr)!
|
||||
wr.write([u8(`]`)])!
|
||||
}
|
||||
time.Time {}
|
||||
Null {
|
||||
wr.write(json2.null_in_bytes)!
|
||||
}
|
||||
@ -176,6 +178,9 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
|
||||
}
|
||||
$if field.typ is string {
|
||||
e.encode_string(value.str(), mut wr)!
|
||||
} $else $if field.typ is time.Time {
|
||||
parsed_time := val.$(field.name) as time.Time
|
||||
e.encode_string(parsed_time.format_rfc3339(), mut wr)!
|
||||
} $else $if field.typ is bool || field.typ is f32 || field.typ is f64 || field.typ is i8
|
||||
|| field.typ is i16 || field.typ is int || field.typ is i64 || field.typ is u8
|
||||
|| field.typ is u16 || field.typ is u32 || field.typ is u64 {
|
||||
@ -215,6 +220,10 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
|
||||
} $else $if field.typ is ?[]int {
|
||||
optional_value := val.$(field.name) as ?[]int
|
||||
e.encode_array(optional_value, level, mut wr)!
|
||||
} $else $if field.typ is ?time.Time {
|
||||
optional_value := val.$(field.name) as ?time.Time
|
||||
parsed_time := optional_value as time.Time
|
||||
e.encode_string(parsed_time.format_rfc3339(), mut wr)!
|
||||
} $else {
|
||||
if field.unaliased_typ != field.typ {
|
||||
match field.unaliased_typ {
|
||||
|
Reference in New Issue
Block a user