2 回答

TA贡献1827条经验 获得超4个赞
JSON 解组time.Time 期望日期字符串为 RFC 3339 格式。
因此,在生成 JSON 的 golang 程序中,不要简单地打印time.Time值,而是使用Format以 RFC 3339 格式打印它。
t.Format(time.RFC3339)
如果我序列化 Time.time 类型,我认为它仍然应该在流程的另一端被理解
如果您使用Marshaller 接口进行序列化,它确实会以 RFC 3339 格式输出日期。所以过程的另一方会理解它。所以你也可以这样做。
d := DataBlob{Datetime: t}
enc := json.NewEncoder(fileWriter)
enc.Encode(d)

TA贡献1111条经验 获得超0个赞
作为参考,如果您需要使用时间类型进行自定义解组,则需要使用 UnmarshallJSON 方法创建自己的类型。带有时间戳的示例
type Timestamp struct {
time.Time
}
// UnmarshalJSON decodes an int64 timestamp into a time.Time object
func (p *Timestamp) UnmarshalJSON(bytes []byte) error {
// 1. Decode the bytes into an int64
var raw int64
err := json.Unmarshal(bytes, &raw)
if err != nil {
fmt.Printf("error decoding timestamp: %s\n", err)
return err
}
// 2 - Parse the unix timestamp
*&p.Time = time.Unix(raw, 0)
return nil
}
然后在你的结构中使用类型:
type DataBlob struct {
....
Datetime Timestamp `json:"datetime"`
....
}
- 2 回答
- 0 关注
- 245 浏览
添加回答
举报