Override the layout used by json.Marshal to format time.Time

前端 未结 3 1733
深忆病人
深忆病人 2021-01-05 07:53

In Golang, is there a way to make the generic encoding/json Marshal to use a different layout when Marshaling the time.Time fields?

Basical

3条回答
  •  天涯浪人
    2021-01-05 08:26

    Maybe something like this will work for you?

    package main
    
    import "fmt"
    import "time"
    import "encoding/json"
    
    type jsonTime struct {
    t time.Time
    f string
    }
    
    func (j jsonTime) MarshalText() ([]byte, error) {
    return []byte(j.t.Format(j.f)), nil
    }
    
    func main() {
    x := map[string]interface{}{
        "foo": jsonTime{t: time.Now(), f: time.Kitchen},
        "bar": "baz",
    }
    data, err := json.Marshal(x)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%s", data)
    }
    

    also available here: http://play.golang.org/p/D1kq5KrXQZ

    Just make a custom type that implements MarshalText the way you want it to show up.

提交回复
热议问题