在Golang中,是否有一种方法可以使通用encoding/json
元帅在编组time.Time
字段时使用不同的布局?
基本上我有这个结构:
s := {"starttime":time.Now(), "name":"ali"}
我想使用encdoding/json
的Marshal
函数编码为json ,但我想使用自定义布局,我想time.Format(layout)
正在调用某个地方,我想控制该布局,
受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, 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方法(在Go 1.2中添加了 MarshalText,MarshalJSON早于此)。结果,使用默认的time.Time格式,而不使用MarshalText提供的自定义格式。
为了克服这个问题,我们为jsonTime结构重写了MarshalJSON。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句