kam*_*mbi 3 json timestamp decode marshalling go
使用此结构运行 Decode() 会产生“timestamp”列错误:
type Metrics struct {
Id int `orm:"column(id);auto"`
Name string `orm:"column(name);size(255);null" json:"metric_name"`
json:"lon"`
Timestamp time.Time `orm:"column(timestamp);type(datetime)" json:"timestamp;omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
错误:
parsing time "1352289160" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1352289160" as """
Run Code Online (Sandbox Code Playgroud)
如何将其解析为 time.Time 值?
谢谢
如果你可以将时间戳设置为unix时间(我假设它是什么),只需将该字段声明为int64,即
type Metrics struct {
...
Timestamp int64 `orm:"column(timestamp);type(datetime)" json:"timestamp;omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
然后你可以将其转换为 Go 的Time类型
var m Metrics
...
When := time.Unix(m.Timestamp, 0)
Run Code Online (Sandbox Code Playgroud)
UnmarshalJSON另一种选择是为 Metrics 类型编写自定义处理程序:
func (this *Metrics) UnmarshalJSON(data []byte) error {
var f interface{}
err := json.Unmarshal(data, &f)
if err != nil { return err; }
m := f.(map[string]interface{})
for k, v := range m {
switch k {
case "metric_name": this.Name = v.(string)
case "timestamp": this.Timestamp = time.Unix(int64(v.(float64)), 0)
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你在结构中就有了正确的 time.Time 值,这使得使用它变得更容易。
| 归档时间: |
|
| 查看次数: |
7873 次 |
| 最近记录: |