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

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

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

问题

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

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

  1. 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.

  1. package main
  2. import (
  3. "encoding/json"
  4. "time"
  5. )
  6. type Time struct {
  7. time.Time
  8. }
  9. func (t *Time) UnmarshalJSON(b []byte) error {
  10. ret, err := time.Parse(time.RFC3339, string(b))
  11. if err != nil {
  12. return err
  13. }
  14. *t = Time{ret}
  15. return nil
  16. }
  17. func (t Time) MarshalJSON() ([]byte, error) {
  18. return []byte(t.UTC().Format(time.RFC3339)), nil
  19. }
  20. func main() {
  21. type User struct {
  22. CreatedAt Time `json:"created_at"`
  23. }
  24. user := User{CreatedAt: Time{time.Now()}}
  25. _, err := json.Marshal(user)
  26. if err != nil {
  27. panic(err)
  28. }
  29. }

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

  1. 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字符串。

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

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.

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

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:

确定