json unmarshal时间不是RFC 3339格式 [英] json unmarshal time that isn't in RFC 3339 format

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

问题描述

在Go中处理不同时间格式的反序列化的适当方法是什么?编码/ 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 自定义类型的接口,并使用它来代替示例

You will have to implement the json.Marshaler / json.Unmarshaler interfaces on a custom type and use that instead, an 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())
}

编辑:添加 CustomTime.IsSet()来检查它是否设置或未设置参考。

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

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

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