非 RFC 3339 格式的 json 解组时间 [英] json unmarshal time that isn't in RFC 3339 format

查看:28
本文介绍了非 RFC 3339 格式的 json 解组时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the appropriate way to handle deserialization of different time formats in Go? The encoding/json package seems to be entirely rigid in only accepted RFC 3339. I can deserialize into a string, transform that into RFC 3339 and then unmarshal it but I don't really want to do that. Any better solutions?

推荐答案

您将必须实施 json.Marshaler/json.Unmarshaler 自定义类型的接口并使用它来代替,一个示例:

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())
}

编辑:添加了 CustomTime.IsSet() 以检查它是否实际设置,以供将来参考.

edit: added CustomTime.IsSet() to check it was actually set or not, for future reference.

这篇关于非 RFC 3339 格式的 json 解组时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆