我正在尝试将一些 json 解码为一个结构并具有以下内容:
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Added struct {
Added *time.Time `json:"added"`
}
func main() {
st := strings.NewReader(`{"added": ""}`)
a := &Added{}
err := json.NewDecoder(st).Decode(&a)
if err != nil {
panic(err)
}
fmt.Println(a)
}
运行上面的结果:
panic: parsing time """" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "2006"
好的,所以我尝试自定义编码器:
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Added struct {
Added *MyTime `json:"added"`
}
func main() {
st := strings.NewReader(`{"added": ""}`)
a := &Added{}
err := json.NewDecoder(st).Decode(&a)
if err != nil {
panic(err)
}
fmt.Println(a)
}
type MyTime struct {
*time.Time
}
func (m *MyTime) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" || string(data) == `""` {
return nil
}
// Fractional seconds are handled implicitly by Parse.
tt, err := time.Parse(`"`+time.RFC3339+`"`, string(data))
*m = MyTime{&tt}
return err
}
然后我得到:
&{%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)}
好的,现在我该怎么办?我只想处理来自 json 的“”值。
我的 playground找到了完整的例子。
最佳答案
import "time"
A Time represents an instant in time with nanosecond precision.
Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time.
我一直在修复可能出现的问题,例如,time.Time
,而不是 *time.Time
,一个真实的日期等等,直到我得到一个合理的结果:
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type MyTime struct {
time.Time
}
func (m *MyTime) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" || string(data) == `""` {
return nil
}
// Fractional seconds are handled implicitly by Parse.
tt, err := time.Parse(`"`+time.RFC3339+`"`, string(data))
*m = MyTime{tt}
return err
}
type Added struct {
Added MyTime `json:"added"`
}
func main() {
st := strings.NewReader(`{"added": "2012-04-23T18:25:43.511Z"}`)
var a Added
err := json.NewDecoder(st).Decode(&a)
if err != nil {
panic(err)
}
fmt.Println(a)
}
Playground :https://play.golang.org/p/Uusdp3DkXDU
输出:
{2012-04-23 18:25:43.511 +0000 UTC}
对于空的 (""
) 日期字符串,time.Time
零值,0001-01-01 00:00:00 +0000 UTC
:
Playground :https://play.golang.org/p/eQoEyqBlhg2
输出:
{0001-01-01 00:00:00 +0000 UTC}
使用time
IsZero
方法来测试零值。
func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
关于go - 解析时间 """"as ""2006-01-02T15 :04:05Z07:0 0"": cannot parse """as "2006",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618633/