【玩轉Golang】 自定義json序列化對象時,非法字符錯誤原因


  由於前台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
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM