非 RFC 3339 格式的 json 解码时间

标签 json go

在 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/

相关文章:

performance - 在Protobuf中将Go结构编码为映射键的最有效方法

c# - Newtonsoft使用类数据结构解析Json数组

go - 可接受的 Golang 惯用嵌套错误处理?

go - 将库更新为特定版本

go - 具有错误行为的模拟功能仍然通过

arrays - 并行处理数组 : any risk of to much threads?

javascript - JSON 嵌套对象与 Javascript 数组

c# - 如何嵌套使用newtonsoft.json

javascript - 双过滤器在 JSON 数组中不起作用

iphone - 解析 JSON 并更改我的模型而不阻塞 UI