在Go中解析奇数JSON日期格式

博·特雷普(Beau Trepp):

我正在调用一个较旧的api,它以的形式返回对象。

{ value: 1, time: "/Date(1412321990000)/" }

使用定义的结构

type Values struct{
  Value int
  Time time.Time
}

给我一个&time.ParseError。我是Go的初学者,有没有一种方法可以定义应如何对其进行序列化/反序列化?最终,我确实希望将其作为time.Time对象。

此日期格式似乎也是较旧的.NET格式。也不能真正改变输出。

jmaloney:

您需要在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
}

查看这个工作示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章