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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器