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条)

报告相同问题?

悬赏问题

  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error