douxing1850 2015-05-21 06:25
浏览 14
已采纳

使用Go解析.Net JSON日期

How can I parse this .Net JSON date with Go? The value comes back unassigned. It appears to parse up to the date field.

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type MyStruct struct {
    FirstField string
    SomeTime time.Time
    LastField string
}

type MyStructSlice struct {
    MyStructs []MyStruct
}

func main() {
    var s MyStructSlice 
    str := `{"MyStructs":[{"FirstField":"123", "SomeTime":"\/Date(1432187580000-0500)\/", "LastField":"456"}]}`
    json.Unmarshal([]byte(str), &s)
    fmt.Println(s)
}

Go Playground

  • 写回答

3条回答 默认 最新

  • dpje52239 2015-05-21 07:00
    关注

    First you model is wrong, it doesn't model the data structure in your JSON. It should be:

    type Data struct {
        Data []MyStruct `json:"data`
    }
    type MyStruct struct {
        SomeTime string
    }
    

    It works with this, try it on the Go Playground.

    Problem is that we still have the time as string.

    Now if you want SomeTime to be time.Time, you need to parse it yourself, you can do it by implementing json.Unmarshaler:

    type Data struct {
        Data []MyStruct `json:"data`
    }
    
    type MyStruct struct {
        SomeTime time.Time
    }
    
    func (m *MyStruct) UnmarshalJSON(data []byte) error {
        // First unmashal it into a string:
        ms := struct{ SomeTime string }{}
        if err := json.Unmarshal(data, &ms); err != nil {
            return err
        }
    
        s := ms.SomeTime
    
        // s is of format: "/Date(1432187580000-0500)/"
        // extract millis and time zone offset hours
        i1 := strings.Index(s, "(")
        i3 := strings.Index(s, ")")
        i2 := strings.Index(s, "-")
        if i2 < 0 {
            i2 = strings.Index(s, "+")
        }
        if i1 < 0 || i2 < 0 || i3 < 0 {
            return errors.New("Invalid format")
        }
    
        millis, err := strconv.ParseInt(s[i1+1:i2], 10, 64)
        if err != nil {
            return err
        }
        m.SomeTime = time.Unix(0, millis*1000000)
    
        // Apply timezone:
        zoneHours, err := strconv.ParseInt(s[i2:i3], 10, 64)
        if err != nil {
            return err
        }
        zone := time.FixedZone("something", int(zoneHours)*3600)
        m.SomeTime = m.SomeTime.In(zone)
        return nil
    }
    

    Try it on the Go Playground.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题