由於前台web頁面傳來的日期對象是這樣的格式“2010-11-03 15:23:22”,所以我安裝網上查來的辦法,自定義包裝了time.Time對象,實現自己的Marshal和UnMarshal方法
type DateTime struct { time.Time } const ctLayout = "2006-01-02 15:04:05" const ctLayout_nosec = "2006-01-02 15:04" const ctLayout_date = "2006-01-02" func (this *DateTime) UnmarshalJSON(b []byte) (err error) { if b[0] == '"' && b[len(b)-1] == '"' { b = b[1 : len(b)-1] } loc, err := time.LoadLocation("Asia/Shanghai") if err != nil { panic(err) } sv := string(b) if len(sv) == 10 { sv += " 00:00:00" } else if len(sv) == 16 { sv += ":00" } this.Time, err = time.ParseInLocation(ctLayout, string(b), loc) if err != nil { if this.Time, err = time.ParseInLocation(ctLayout_nosec, string(b), loc); err != nil { this.Time, err = time.ParseInLocation(ctLayout_date, string(b), loc) } } return } func (this *DateTime) MarshalJSON() ([]byte, error) { rs := []byte(this.Time.Format(ctLayout)) return rs, nil } var nilTime = (time.Time{}).UnixNano() func (this *DateTime) IsSet() bool { return this.UnixNano() != nilTime }
然后,把結構中聲明為time.Time的都修改為自定義的類型DateTime,試了一下,發現已經可以正確解析網頁發來的時間,但是在輸出時,總是不對,好像並沒有調用自定義的Marshal方法。編寫測試方法發現,原來json.Marshal方法調用DateTime.Marshal時出錯了!
invalid character '-' after top-level value
開始沒有認真看,以為“-”號不合法,就換了一個,結果錯誤一樣:
invalid character '/' after top-level value
看來,根本不是分割符的問題,仔細分析錯誤,發現“top-level”字樣,我這返回的就是一個字符串,怎么可能top-level呢!想到這兒突然醒悟,是不是返回字符串應該自己加引號呢,急忙修改代碼一試,果然!~_~
最終代碼如下:
type DateTime struct { time.Time } const ctLayout = "2006-01-02 15:04:05" const ctLayout_nosec = "2006-01-02 15:04" const ctLayout_date = "2006-01-02" func (this *DateTime) UnmarshalJSON(b []byte) (err error) { if b[0] == '"' && b[len(b)-1] == '"' { b = b[1 : len(b)-1] } loc, err := time.LoadLocation("Asia/Shanghai") if err != nil { panic(err) } sv := string(b) if len(sv) == 10 { sv += " 00:00:00" } else if len(sv) == 16 { sv += ":00" } this.Time, err = time.ParseInLocation(ctLayout, string(b), loc) if err != nil { if this.Time, err = time.ParseInLocation(ctLayout_nosec, string(b), loc); err != nil { this.Time, err = time.ParseInLocation(ctLayout_date, string(b), loc) } } return } func (this *DateTime) MarshalJSON() ([]byte, error) { rs := []byte(fmt.Sprintf(`"%s"`, this.Time.Format(ctLayout))) return rs, nil } var nilTime = (time.Time{}).UnixNano() func (this *DateTime) IsSet() bool { return this.UnixNano() != nilTime }
