古老的榕树

Go 语言 json 的时间格式化

潘军杰 发表于 2016-04-14 23:35 阅读(5665) 评论(0) 赞(1)
Go 语言开发 reset 的接口,结构体转成 json 的时间都是带时区信息的,这并不是我们想要的,例如:

结构体:
type Article struct {
WebSite string
Title    string
Created  time.Time
}

结构体实例转成 json 后,结构:
{"Created":"2016-03-20T20:44:25.371Z","Title":"测试标题5","WebSite":"5-wow.com"}

实际上我们需要这样的 json:
{"Created":"2016-03-20 20:44:25","Title":"测试标题5","WebSite":"5-wow.com"}

以下是一种解决方案,对结构体的 Created 字段的类型 time.Time 进行封装,现在定义一种类型,继承于 time.Time 类,如下:

type JSONTime time.Time

func (t JSONTime) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf(`"%s"`, time.Time(t).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}


然后把 Article 结构体的 Created 定义成 JSONTime 类型,如下:

type Article struct {
WebSite string
Title    string
Created  JSONTime
}

最后把 Article 实例转成 json,结果就是我们想要的了:
{"Created":"2016-03-20 20:44:25","Title":"测试标题5","WebSite":"5-wow.com"}


(完)

0 条网友评论

哇~~~ 竟然还没有评论!

称呼*
邮箱*
内容*
验证码*
验证码 看不清换张