V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hunk
V2EX  ›  Go 编程语言

json 中的时间转 struct 问题

  •  
  •   hunk · 2021-08-16 10:26:53 +08:00 · 699 次点击
    这是一个创建于 956 天前的主题,其中的信息可能已经有所发展或是发生改变。
    问题 1:
    json 中的时间格式不标准"create_time":"2021-08-14 11:36:37"
    在转为 struct 时,不能直接转为 time.Time 。
    网上找了别人写好的 UnmarshalJSON 方法,依然不能解析。

    问题 2:
    将 struct 改为 string,输出是空。
    在 go 中,json.Unmarshal 解析前的代码是 bytes 数组。手动执行 curl,得到的结果是有的。
    wfhtqp
        1
    wfhtqp  
       2021-08-16 14:03:24 +08:00
    自定义类型并实现 Unmarshal/Marshal 方法
    danc
        2
    danc  
       2021-08-17 00:47:40 +08:00
    ```go
    package util

    import "time"

    func ParseTime(value string) (time.Time, error) {
    loc := time.FixedZone("UTC+8", +8*60*60)

    return time.ParseInLocation("2006-01-02 15:04:05", value, loc)
    }

    func TimeFormat(t time.Time) string {
    loc := time.FixedZone("UTC+8", +8*60*60)
    return t.In(loc).Format("2006-01-02 15:04:05")
    }

    type MyTime time.Time

    func (myT MyTime) MarshalText() (data []byte, err error) {
    t := time.Time(myT)
    data = []byte(TimeFormat(t))
    return
    }

    func (myT *MyTime) UnmarshalText(text []byte) (err error) {
    t := (*time.Time)(myT)
    *t, err = ParseTime(string(text))
    return
    }
    ```

    然后

    ```go
    type MonitorDiagnosisItem struct {
    Time util.MyTime `json:"time"`
    }
    ```

    学会了吗?
    hunk
        3
    hunk  
    OP
       2021-08-17 15:15:52 +08:00
    好详细,谢谢。我用了两个 struct 做转换,回头试试这种写法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5339 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:29 · PVG 16:29 · LAX 01:29 · JFK 04:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.