問題
我們知道go語言的time.Time類型在轉為json的時候,輸出的是UTC的時間,而我們絕大部分時候使用的都是Datetime格式。
其實解決問題的核心就是使用自定義字段,實現json的MarshaJSON方法
一、示例:原生time.Time的json輸出為UTC格式
例如,我們有一個商品結構體Good,里邊的CreatedAt和UpdateAt為time.Time類型
package main
import (
"encoding/json"
"fmt"
"time"
)
type Good struct {
ID int `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func main() {
good := Good{123, "chenqiognhe", time.Now(), time.Now()}
bytes, _ := json.Marshal(good)
fmt.Printf("%s", bytes)
}
輸出結果為
{
"id": 123,
"name": "chenqiognhe",
"created_at": "2020-07-31T14:27:10.035542+08:00",
"updated_at": "2020-07-31T14:27:10.035542+08:00"
}
可以看到created_at和updated_at都是UTC的格式
二、自定義結構體Datetime(缺點是需要手動轉換類型)
如下,我們定義了一個time.Time的別名結構體Datetime
package main
import (
"encoding/json"
"fmt"
"time"
)
type Datetime time.Time
func (t Datetime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}
type Good struct {
ID int `json:"id"`
Name string `json:"name"`
CreatedAt Datetime `json:"created_at"`
UpdatedAt Datetime `json:"updated_at"`
}
func main() {
good := Good{123, "chenqiognhe", Datetime(time.Now()), Datetime(time.Now())}
bytes, _ := json.Marshal(good)
fmt.Printf("%s", bytes)
}
輸出如下
{
"id": 123,
"name": "chenqiognhe",
"created_at": "2020-07-31 14:27:39",
"updated_at": "2020-07-31 14:27:39"
}
三、自定義結構體Datetime+自定義臨時結構體(最佳方案)
package main
import (
"encoding/json"
"fmt"
"time"
)
type DateTime time.Time
func (t DateTime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%s\"", time.Time(t).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}
type Good struct {
ID int `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (t Good) MarshalJSON() ([]byte, error) {
type TmpJSON Good
return json.Marshal(&struct {
TmpJSON
CreatedAt DateTime `json:"created_at"`
UpdatedAt DateTime `json:"updated_at"`
}{
TmpJSON: (TmpJSON)(t),
CreatedAt: DateTime(t.CreatedAt),
UpdatedAt: DateTime(t.UpdatedAt),
})
}
func main() {
good := Good{123, "chenqiognhe", time.Now(), time.Now()}
bytes, _ := json.Marshal(good)
fmt.Printf("%s", bytes)
}
這里我們給Good加了一個MarshalJSON方法實現,並通過臨時結構體TmpJSON,指定了CreatedAt和UpdatedAt字段為Datetime類型。
使用Good結構體,無需轉換time.Time為Datetime,可以直接使用time.Time的所有方法。
輸出結果為
{
"id": 123,
"name": "chenqiognhe",
"created_at": "2020-07-31 14:28:12",
"updated_at": "2020-07-31 14:28:12"
}