2 回答

TA貢獻1827條經(jīng)驗 獲得超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條經(jīng)驗 獲得超0個贊
作為參考,如果您需要使用時間類型進行自定義解組,則需要使用 UnmarshallJSON 方法創(chuàng)建自己的類型。帶有時間戳的示例
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
}
然后在你的結(jié)構中使用類型:
type DataBlob struct {
....
Datetime Timestamp `json:"datetime"`
....
}
- 2 回答
- 0 關注
- 238 瀏覽
添加回答
舉報