json: 调用 main.Time 的 MarshalJSON 方法时出错:顶级值后面有无效字符 ‘-‘

huangapple go评论99阅读模式
英文:

json: error calling MarshalJSON for type main.Time: invalid character '-' after top-level value

问题

我打算将time.Time序列化为UTC时区并使用RFC3339格式。所以我创建了一个名为Time的自定义数据类型,它嵌入了time.Time

当尝试使用json.Marshal对这个数据进行编组时,我得到以下错误:

json: error calling MarshalJSON for type main.Time: invalid character '-' after top-level value

我有两个问题:

  1. 为什么上面的代码会报错?
  2. 这是在API中将time.Time序列化和反序列化为所需格式的正确方法吗?

谢谢!

英文:

I intent to serialize time.Time to have UTC timezone and in RFC3339 format.
So I created following custom data type called Time that embeds time.Time.

package main

import (
	"encoding/json"
	"time"
)

type Time struct {
	time.Time
}

func (t *Time) UnmarshalJSON(b []byte) error {
	ret, err := time.Parse(time.RFC3339, string(b))
	if err != nil {
		return err
	}
	*t = Time{ret}
	return nil
}

func (t Time) MarshalJSON() ([]byte, error) {
	return []byte(t.UTC().Format(time.RFC3339)), nil
}

func main() {
	type User struct {
		CreatedAt Time `json:"created_at"`
	}

	user := User{CreatedAt: Time{time.Now()}}
	_, err := json.Marshal(user)
	if err != nil {
		panic(err)
	}
}

When this data is tried to marshal with json.Marshal I get following error

json: error calling MarshalJSON for type main.Time: invalid character '-' after top-level value

I have 2 queries

  1. Why above code is throwing the error?
  2. Is this the right way to serialise and deserialise time.Time to and from a desired format in an API

Thanks in advance!

答案1

得分: 4

文本2009-11-10T23:00:00Z不是有效的JSON值,但"2009-11-10T23:00:00Z"是。请注意引号。

使用以下函数将时间格式化为JSON字符串。

func (t Time) MarshalJSON() ([]byte, error) {
    b := make([]byte, 0, len(time.RFC3339)+2)
    b = append(b, '"')
    b = t.AppendFormat(b, time.RFC3339)
    b = append(b, '"')
    return b, nil
}
英文:

The text 2009-11-10T23:00:00Z is not a valid JSON value, but "2009-11-10T23:00:00Z" is. Note the quotes.

Use the following function to format Time as a JSON string.

func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(time.RFC3339)+2)
	b = append(b, '"')
	b = t.AppendFormat(b, time.RFC3339)
	b = append(b, '"')
	return b, nil
}

huangapple
  • 本文由 发表于 2022年3月9日 14:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/71405282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定