有時(shí)候項(xiàng)目開發(fā)會(huì)遇到一個(gè)結(jié)構(gòu)體的Json轉(zhuǎn)換的時(shí)間格式問題。 即這種1993-01-01T20:08:23.000000028+08:00 這種表示UTC方法。從我們習(xí)慣來說,更喜歡希望的是 1993-01-01 20:08:23這種格式。 重新復(fù)現(xiàn)代碼如下:
package main
import (
"time"
"encoding/json"
)
type Student struct {
Name string `json:"name"`
Brith time.Time `json:"brith"`
}
func main() {
stu:=Student{
Name:"qiangmzsx",
Brith:time.Date(1993, 1, 1, 20, 8, 23, 28, time.Local),
}
b,err:=json.Marshal(stu)
if err!=nil {
println(err)
}
println(string(b))//{"name":"qiangmzsx","brith":"1993-01-01T20:08:23.000000028+08:00"}
}
遇到這樣的問題,那么Golang是如何解決的呢? 有兩種解決方案,下面我們一個(gè)個(gè)來看看。
通過time.Time類型別名
type JsonTime time.Time
// 實(shí)現(xiàn)它的json序列化方法
func (this JsonTime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%s\"", time.Time(this).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}
type Student1 struct {
Name string `json:"name"`
Brith JsonTime `json:"brith"`
}
func main() {
stu1:=Student1{
Name:"qiangmzsx",
Brith:JsonTime(time.Date(1993, 1, 1, 20, 8, 23, 28, time.Local)),
}
b1,err:=json.Marshal(stu1)
if err!=nil {
println(err)
}
println(string(b1))//{"name":"qiangmzsx","brith":"1993-01-01 20:08:23"}
}
使用結(jié)構(gòu)體組合方式
相較于第一種方式,該方式顯得復(fù)雜一些。
type Student2 struct {
Name string `json:"name"`
// 一定要將json的tag設(shè)置忽略掉不解析出來
Brith time.Time `json:"-"`
}
// 實(shí)現(xiàn)它的json序列化方法
func (this Student2) MarshalJSON() ([]byte, error) {
// 定義一個(gè)該結(jié)構(gòu)體的別名
type AliasStu Student2
// 定義一個(gè)新的結(jié)構(gòu)體
tmpStudent:= struct {
AliasStu
Brith string `json:"brith"`
}{
AliasStu:(AliasStu)(this),
Brith:this.Brith.Format("2006-01-02 15:04:05"),
}
return json.Marshal(tmpStudent)
}
func main() {
stu2:=Student2{
Name:"qiangmzsx",
Brith:time.Date(1993, 1, 1, 20, 8, 23, 28, time.Local),
}
b2,err:=json.Marshal(stu2)
if err!=nil {
println(err)
}
println(string(b2))//{"name":"qiangmzsx","brith":"1993-01-01 20:08:23"}
}
該方法使用了Golang的結(jié)構(gòu)體的組合方式,可以實(shí)現(xiàn)OOP的繼承,也是體現(xiàn)Golang靈活。
對(duì)任意struct增加 MarshalJSON ,UnmarshalJSON , String 方法,實(shí)現(xiàn)自定義json輸出格式與打印方式。