在Go中解析奇怪的JSON日期格式

Bea*_*epp 3 json go

我正在调用一个较老的api,并以其形式返回它的对象.

{ value: 1, time: "/Date(1412321990000)/" }
Run Code Online (Sandbox Code Playgroud)

使用定义的结构

type Values struct{
  Value int
  Time time.Time
}
Run Code Online (Sandbox Code Playgroud)

给我一个&time.ParseError.我是Go的初学者,有没有办法让我定义如何序列化/反序列化?最终我确实希望它作为time.Time对象.

这种日期格式似乎也是一种较旧的.NET格式.无法真正改变输出.

jma*_*ney 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
}
Run Code Online (Sandbox Code Playgroud)

看看这个工作示例.