在Golang中,是否有一种方法可以使通用编码/ json Marshal在编组time.Time字段时使用不同的布局?
基本上我有这个结构:
- s := {"starttime":time.Now(),"name":"ali"}
我想使用encdoding / json的Marshal函数对json进行编码,但是我想使用我的自定义布局,我想某个时候.正在调用格式(布局),我想控制那个布局,
解决方法
受到zeebo答案的启发,并在对该答案的评论中加以说明:
http://play.golang.org/p/pUCBUgrjZC
- package main
- import "fmt"
- import "time"
- import "encoding/json"
- type jsonTime struct {
- time.Time
- f string
- }
- func (j jsonTime) format() string {
- return j.Time.Format(j.f)
- }
- func (j jsonTime) MarshalText() ([]byte,error) {
- return []byte(j.format()),nil
- }
- func (j jsonTime) MarshalJSON() ([]byte,error) {
- return []byte(`"` + j.format() + `"`),nil
- }
- func main() {
- jt := jsonTime{time.Now(),time.Kitchen}
- if jt.Before(time.Now().AddDate(0,1)) { // 1
- x := map[string]interface{}{
- "foo": jt,"bar": "baz",}
- data,err := json.Marshal(x)
- if err != nil {
- panic(err)
- }
- fmt.Printf("%s",data)
- }
- }
这个解决方案embeds将time.Time放入jsonTime结构中.嵌入促进了jsonTime结构的所有time.Time方法,允许它们在没有显式类型转换的情况下使用(参见// 1).
嵌入time.Time还有一个缺点就是提升MarshalJSON方法,为了向后兼容性原因,编码/ json封送代码优先于MarshalText方法(MarshalText was added in Go 1.2,MarshalJSON早于此).因此,使用默认的time.Time格式而不是MarshalText提供的自定义格式.
为了解决这个问题,我们为jsonTime结构重写了MarshalJSON.