Golang time.Time.UnmarshalJSON()函数及示例
在Golang中,时间与日期是很常用的数据类型,而Json通信在实际项目中也是相当常见的场景。我们就来了解一下Golang中time.Time.UnmarshalJSON()函数的使用。
time.Time.UnmarshalJSON() 函数简介
unmarshalJSON方法的源码如下:
func (t *Time) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
if len(str) == 0 || str == "null" {
*t = Time{}
return nil
}
parsed, err := Parse(`"`+TimeFormat+`"`, str)
if err != nil {
return err
}
*t = parsed
return nil
}
time.Time.UnmarshalJSON() 函数使用示例
示例代码:
package main
import (
"encoding/json"
"fmt"
"time"
)
// Article represents a post
type Article struct {
ID int `json:"id"`
Title string `json:"title"`
Published time.Time `json:"published"`
}
func main() {
jsonStr := `[
{
"id": 1,
"title": "Post 1",
"published": "2021-08-02T15:04:05-07:00"
},
{
"id": 2,
"title": "Post 2",
"published": "2021-08-03T10:11:12-07:00"
},
{
"id": 3,
"title": "Post 3",
"published": "2021-08-04T12:13:14-07:00"
}
]`
var articles []Article
err := json.Unmarshal([]byte(jsonStr), &articles)
if err != nil {
panic(err)
}
for _, article := range articles {
fmt.Printf("Title: %s\nPublished: %v\n\n", article.Title, article.Published)
}
}
以上代码将一个包含了文章的JSON字符串解析成一个结构体数组,并输出解析后的结果。
注意,这里的时间戳格式是 RFC3339Nano
,因此在结构体中需要把 Published 字段定义为 time.Time 类型,同时使用 json 标签指定 Published 字段在 JSON 中的名称为 “published”。这个时间戳包含了时区信息,因此可以通过转换成 time.Time 类型,进行随意的格式化等操作。
结论
通过以上示例代码,我们了解到如何使用 Golang 中的 time.Time.UnmarshalJSON()
函数,将 Json 格式的时间转换成 Golang 中的 time.Time 类型,使我们能够在程序中方便地进行与时间相关的操作。