我怎样才能在 json 中响应时间毫秒零

在我的 mongodb 中,我有字段

"createdAt" : ISODate("2018-10-02T01:17:58.000Z")

我有结构有字段

CreatedAt      time.Time       `json:"createdAt" bson:"createdAt"`

但是当我通过 json 响应时,它缺少我预期的零毫秒

"createdAt": "2018-10-02T01:17:58.000Z"

但收到

"createdAt": "2018-10-02T01:17:58Z"


慕标5832272
浏览 89回答 1
1回答

ibeautiful

来自 golang.org/pkg/time/#Time.MarshalJSON:时间是 RFC 3339 格式的带引号的字符串,如果存在则添加亚秒级精度。零是无关紧要的,所以它们被省略了。如果这对您不起作用,请实施您自己的 MarshalJSON 方法:package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")type MyType struct {&nbsp; &nbsp; Foo&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; CreatedAt time.Time `json:"-" bson:"createdAt"`}func (t MyType) MarshalJSON() ([]byte, error) {&nbsp; &nbsp; type MyType_ MyType // prevent recursion&nbsp; &nbsp; return json.Marshal(struct {&nbsp; &nbsp; &nbsp; &nbsp; MyType_&nbsp; &nbsp; &nbsp; &nbsp; CreatedAt string `json:"createdAt"` // Override time field&nbsp; &nbsp; }{&nbsp; &nbsp; &nbsp; &nbsp; MyType_(t),&nbsp; &nbsp; &nbsp; &nbsp; t.CreatedAt.Format("2006-01-02T15:04:05.000Z07:00"),&nbsp; &nbsp; })}func main() {&nbsp; &nbsp; t := MyType{&nbsp; &nbsp; &nbsp; &nbsp; Foo:&nbsp; &nbsp; &nbsp; &nbsp;"bar",&nbsp; &nbsp; &nbsp; &nbsp; CreatedAt: time.Date(2018, 10, 2, 12, 13, 14, 0, time.UTC),&nbsp; &nbsp; }&nbsp; &nbsp; b, err := json.MarshalIndent(t, "", "&nbsp; ")&nbsp; &nbsp; fmt.Println(err, string(b))&nbsp; &nbsp; t.CreatedAt = t.CreatedAt.Add(123456 * time.Microsecond)&nbsp; &nbsp; b, err = json.MarshalIndent(t, "", "&nbsp; ")&nbsp; &nbsp; fmt.Println(err, string(b))}// Output:// <nil> {//&nbsp; &nbsp;"Foo": "bar",//&nbsp; &nbsp;"T": "2018-10-02T12:13:14.000Z"// }// <nil> {//&nbsp; &nbsp;"Foo": "bar",//&nbsp; &nbsp;"T": "2018-10-02T12:13:14.123Z"// }https://play.golang.org/p/bmDk1pejGPS如果你必须在很多地方这样做,创建你自己的时间类型可能是值得的(如果你必须做日期数学,那将是不方便的,虽然):type MyType struct {&nbsp; &nbsp; &nbsp; &nbsp; Foo&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; &nbsp; &nbsp; CreatedAt MyTime `json:"createdAt" bson:"createdAt"`}type MyTime struct {&nbsp; &nbsp; &nbsp; &nbsp; time.Time}func (t MyTime) MarshalJSON() ([]byte, error) {&nbsp; &nbsp; &nbsp; &nbsp; return json.Marshal(t.Format("2006-01-02T15:04:05.000Z07:00"))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go