我正在调用一个较旧的api,它的返回对象是。
{ value: 1, time: "/Date(1412321990000)/" }
使用用
定义的结构type Values struct{
Value int
Time time.Time
}
给我一个& time.ParseError。我是Go的初学者,有没有办法让我定义如何序列化/反序列化?最终我确实希望它作为一个时间。时间对象。
这种日期格式似乎也是一种较旧的.NET格式。无法真正改变输出。
答案 0 :(得分:5)
您需要在Values结构上实现json Unmarshaler接口。
// UnmarshalJSON implements json's Unmarshaler interface
func (v *Values) UnmarshalJSON(data []byte) error {
// create tmp struct to unmarshal into
var tmp struct {
Value int `json:"value"`
Time string `json:"time"`
}
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
v.Value = tmp.Value
// trim out the timestamp
s := strings.TrimSuffix(strings.TrimPrefix(tmp.Time, "/Date("), ")/")
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
// create and assign time using the timestamp
v.Time = time.Unix(i/1000, 0)
return nil
}
查看此工作example。
答案 1 :(得分:1)
另一种方法是定义时间的自定义类型,而不是手动创建临时结构。
同时嵌入time.Time可以更轻松地访问其上定义的所有函数,例如.String()
。
type WeirdTime struct{ time.Time }
type Value struct {
Value int
Time WeirdTime
}
func (wt *WeirdTime) UnmarshalJSON(data []byte) error {
if len(data) < 9 || data[6] != '(' || data[len(data)-3] != ')' {
return fmt.Errorf("unexpected input %q", data)
}
t, err := strconv.ParseInt(string(data[7:len(data)-3]), 10, 64)
if err != nil {
return err
}
wt.Time = time.Unix(t/1000, 0)
return nil
}