这篇文章主要为大家展示了“golang如何使用MarshalJSON支持time.Time”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“golang如何使用MarshalJSON支持time.Time”这篇文章吧。
使用 MarshalJSON支持time.Time
golang 默认会把 time.Time
用字符串方式序列化。如果我们想用其他方式表示 time.Time
,需要自定义类型并定义 MarshalJSON。
type timeImplementedMarshaler time.Time func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) { seconds := time.Time(obj).Unix() return []byte(strconv.FormatInt(seconds, 10)), nil }
序列化的时候会调用 MarshalJSON
type TestObject struct { Field timeImplementedMarshaler } should := require.New(t) val := timeImplementedMarshaler(time.Unix(123, 0)) obj := TestObject{val} bytes, err := jsoniter.Marshal(obj) should.Nil(err) should.Equal(`{"Field":123}`, string(bytes))
以上是“golang如何使用MarshalJSON支持time.Time”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注云搜网行业资讯频道!