【玩转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
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值