受zeebo的回答启发,并在该评论的注释中进行了散列:
http://play.golang.org/p/pUCBUgrjZC
package mainimport "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, 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) }}此解决方案将 time.Time
嵌入
jsonTime结构中。嵌入将所有time.Time方法提升为jsonTime结构,从而允许其使用而无需显式类型转换(请参见// 1)。
嵌入time.Time也不利于推广MarshalJSON方法,出于向后兼容的原因,编码/
json封送处理代码对MarshalText方法的优先级高于MarshalText方法(MarshalText是在Go
1.2中添加的,MarshalJSON
在此之前)。结果,使用默认的time.Time格式,而不使用MarshalText提供的自定义格式。
为了克服这个问题,我们为jsonTime结构覆盖了MarshalJSON。



