英文:
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
我有两个问题:
- 为什么上面的代码会报错?
- 这是在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
- Why above code is throwing the error?
- 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论