gpt4 book ai didi

非 RFC 3339 格式的 json 解码时间

转载 作者:IT老高 更新时间:2023-10-28 12:48:07 26 4
gpt4 key购买 nike

在 Go 中处理不同时间格式的反序列化的适当方法是什么? encoding/json 包在仅接受的 RFC 3339 中似乎完全僵化。我可以反序列化为字符串,将其转换为 RFC 3339,然后对其进行解码,但我真的不想这样做。有更好的解决方案吗?

最佳答案

您必须执行 json.Marshaler/json.Unmarshaler自定义类型上的接口(interface)并使用它来代替,example :

type CustomTime struct {
time.Time
}

const ctLayout = "2006/01/02|15:04:05"

func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b), "\"")
if s == "null" {
ct.Time = time.Time{}
return
}
ct.Time, err = time.Parse(ctLayout, s)
return
}

func (ct *CustomTime) MarshalJSON() ([]byte, error) {
if ct.Time.UnixNano() == nilTime {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("\"%s\"", ct.Time.Format(ctLayout))), nil
}

var nilTime = (time.Time{}).UnixNano()
func (ct *CustomTime) IsSet() bool {
return ct.UnixNano() != nilTime
}

type Args struct {
Time CustomTime
}

var data = `
{"Time": "2014/08/01|11:27:18"}
`

func main() {
a := Args{}
fmt.Println(json.Unmarshal([]byte(data), &a))
fmt.Println(a.Time.String())
}

edit:添加 CustomTime.IsSet() 以检查它是否实际设置,以供将来引用。

关于非 RFC 3339 格式的 json 解码时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25087960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com