dtup3446 2014-10-06 00:22
浏览 41
已采纳

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

I'm calling a older api, and its returning objects in the form of.

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

Using a struct defined with

type Values struct{
  Value int
  Time time.Time
}

Gives me a &time.ParseError. I'm a beginner at Go, is there a way for me to define how this should be serialized/deserialized?. Ultimately I do want it as a time.Time object.

This date format seems to be an older .NET format too. Can't really get the output changed either.

  • 写回答

2条回答 默认 最新

  • doujizhong8352 2014-10-06 01:08
    关注

    You need to implement the json Unmarshaler interface on your Values struct.

    // 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
    }
    

    Check out this working example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算