我正在尝试使用时间值解组 JSON。我有这个 JSON 结构。{ "Nick": "cub", "Email": "cub875@rambler.ru", "Created_at": "2017-10-09", "Subscribers": [ { "Email": "rat1011@rambler.ru", "Created_at": "2017-11-30" }, { "Email": "hound939@rambler.ru", "Created_at": "2016-07-15" }, { "Email": "worm542@rambler.ru", "Created_at": "2017-02-16" }, { "Email": "molly1122@rambler.ru", "Created_at": "2016-11-30" }, { "Email": "goat1900@yandex.ru", "Created_at": "2018-07-10" }, { "Email": "duck1146@rambler.ru", "Created_at": "2017-09-04" }, { "Email": "eagle1550@mail.ru", "Created_at": "2018-01-03" }, { "Email": "prawn1755@rambler.ru", "Created_at": "2018-04-20" }, { "Email": "platypus64@yandex.ru", "Created_at": "2018-02-17" } ] }以及一个实现从 JSON 文件读取到 struct User 的函数。一切都很好,但是当我将 User 结构中的 CreatedAt 字段设置为 time.Time 类型时,我会为 JSON 文件中类型格式的每个字段获得 0001-01-01 00:00:00 +0000 UTC 值。type Subscriber struct { Email string `json: "Email"` CreatedAt time.Time `json: "Created_at"`}type User struct { Nick string `json: "Nick"` Email string `json: "Email"` CreatedAt string `json: "Created_at"` Subscribers []Subscriber `json: "Subscribers"`}}以 RFC3339 格式从 JSON 文件读取时间到用户的合适方法是什么?
1 回答
慕村9548890
TA贡献1884条经验 获得超4个赞
您可以使用实现json.Unmarshaler接口的自定义时间类型。
你可以从这个结构开始:
type CustomTime struct {
time.Time // Embed time.Time to allow calling of normal time.Time methods
}
然后添加所需的UnmarshalJSON([]byte) error功能。它可能看起来像这样:
func (c *CustomTime) UnmarshalJSON(b []byte) error {
if len(b) < 3 {
// Empty string: ""
return fmt.Errorf("Empty time value")
}
t, err := time.Parse("2006-01-02", string(b[1:len(b)-1])) // b[1:len(b)-1] removes the first and last character, as they are quotes
if err != nil {
return err
}
c.Time = t
return nil
}
您可以在Go Playground上尝试该示例
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报
0/150
提交
取消