This is a creation in Article, where the information may have evolved or changed.
Because the foreground web page came from the date object is such a format "2010-11-03 15:23:22", so I installed the online search method, custom wrapped time. Time object to implement your own marshal and Unmarshal methods
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) {ifB[0] = ='"'&& B[len (b)-1] = ='"'{b= B[1:len (b)-1]} loc, err:= time. Loadlocation ("Asia/shanghai") ifErr! =Nil {panic (err)} SV:=string (b)ifLen (SV) = = 10{SV+="00:00:00" } Else ifLen (SV) = = 16{SV+=": xx"} this. Time, Err=Time . Parseinlocation (Ctlayout, string (b), loc)ifErr! =Nil {ifThis. 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))returnRS, Nil}var niltime=(time. time{}). Unixnano () func ( this*DateTime) IsSet () bool {returnThis. Unixnano ()! =Niltime}
Then, declare the structure as time. Time is modified to a custom type DateTime, tried, found that the page has been able to correctly parse the times, but the output is always wrong, as if the custom marshal method is not called. Writing the test method found that the original JSON. Marshal method called Datetime.marshal Error!
' - '
At first did not look seriously, thought "-" number is illegal, changed one, the result is the same:
' / '
It seems that is not the problem of the division, careful analysis of the error, found the word "top-level", I returned is a string, how can top-level it! Think of here suddenly wake up, is not the return string should be quoted, hurriedly modify the code a try, sure enough! ~_~
The final code is as follows:
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) {ifB[0] = ='"'&& B[len (b)-1] = ='"'{b= B[1:len (b)-1]} loc, err:= time. Loadlocation ("Asia/shanghai") ifErr! =Nil {panic (err)} SV:=string (b)ifLen (SV) = = 10{SV+="00:00:00" } Else ifLen (SV) = = 16{SV+=": xx"} this. Time, Err=Time . Parseinlocation (Ctlayout, string (b), loc)ifErr! =Nil {ifThis. 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)))returnRS, Nil}var niltime=(time. time{}). Unixnano () func ( this*DateTime) IsSet () bool {returnThis. Unixnano ()! =Niltime}