Time format solution for Golang structure JSON

Source: Internet
Author: User
Tags sprintf string methods
This is a creation in Article, where the information may have evolved or changed.

Using the OSC so long has not written a blog post, true shame! Write down the first article at a time.
A recent development project found a time format problem for JSON conversion of a struct. That is, this 1993-01-01t20:08:23.000000028+08:00 represents the UTC method. From what we used to say, the more like hope is 1993-01-01 20:08:23 this format. The re-replication code is as follows:

package mainimport (    "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"}}

In the face of such problems, how is Golang solved? There are two kinds of solutions, let's take a look at each one.

Through time. Time Type Alias

type JsonTime time.Time// 实现它的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"}}

Using struct-body combination methods

It's a bit more complicated than the first, and I'm not recommending it as an extended tutorial.

type Student2 struct {    Name string     `json:"name"`    // 一定要将json的tag设置忽略掉不解析出来    Brith time.Time  `json:"-"`}// 实现它的json序列化方法func (this Student2) MarshalJSON() ([]byte, error) {    // 定义一个该结构体的别名    type AliasStu Student2    // 定义一个新的结构体    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"}}

This method uses the combination of Golang structure, can realize the inheritance of OOP, but also embodies golang flexibility.

Below, the above code is composed of the whole.

Package Mainimport ("Time" "Encoding/json"//"FMT" "FMT") type Student struct {name string ' JSON: "Name "' Brith time. Time ' JSON: "Brith" '}type jsontime time. TIME//implements its JSON serialization method, 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 ' ' Bri Th jsontime ' JSON: "Brith" '}type Student2 struct {name string ' JSON: "name" '//Must ignore the JSON's tag settings and not parse it out Brith Time. Time ' JSON: '-'}//implements its JSON serialization method Func (this Student2) Marshaljson ([]byte, error) {//defines an alias for the struct type Aliasstu S Tudent2//define a new struct 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 () {stu:=student{Name: "Qiangmzsx", Brith:time. Date (1993, 1, 1, 8, Max, Max, time. Local),} b,err:=json. Marshal (stu) if Err!=nil {println (Err)} println (string (b))//{"name": "Qiangmzsx", "Brith": "1993-01-01t20:0 8:23.000000028+08:00 "} println (" =================== ") stu1:=student1{Name:" Qiangmzsx ", Brith:jsontime (Time. Date (1993, 1, 1, 8,. Local),} b1,err:=json. Marshal (STU1) if Err!=nil {println (Err)} println (String (B1))//{"name": "Qiangmzsx", "Brith": "1993-01-01 20 : 08:23 "} println (" =================== ") stu2:=student2{Name:" Qiangmzsx ", Brith:time. Date (1993, 1, 1, 8,. Local),} b2,err:=json. Marshal (STU2) if Err!=nil {println (Err)} println (String (b2))//{"name": "Qiangmzsx", "Brith": "1993-01-01 20 : 08:23 "}}

It is worth mentioning that adding Marshaljson, Unmarshaljson, and String methods to any struct implements a custom JSON output format and printing method.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.