json 中的时间转 struct 问题

2021-08-16 10:26:53 +08:00
 hunk
问题 1:
json 中的时间格式不标准"create_time":"2021-08-14 11:36:37"
在转为 struct 时,不能直接转为 time.Time 。
网上找了别人写好的 UnmarshalJSON 方法,依然不能解析。

问题 2:
将 struct 改为 string,输出是空。
在 go 中,json.Unmarshal 解析前的代码是 bytes 数组。手动执行 curl,得到的结果是有的。
733 次点击
所在节点    Go 编程语言
3 条回复
wfhtqp
2021-08-16 14:03:24 +08:00
自定义类型并实现 Unmarshal/Marshal 方法
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
2021-08-17 15:15:52 +08:00
好详细,谢谢。我用了两个 struct 做转换,回头试试这种写法

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/796002

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX