为了账号安全,请及时绑定邮箱和手机立即绑定

时间 JSON 编组为 0 时间

时间 JSON 编组为 0 时间

Go
慕莱坞森 2023-06-19 15:35:01
我有以下代码,主要编组和取消编组时间结构。这是代码package mainimport (    "fmt"    "time"    "encoding/json")type check struct{    A time.Time `json:"a"`}func main(){    ds := check{A:time.Now().Truncate(0)}    fmt.Println(ds)    dd, _ := json.Marshal(ds)    d2 := check {}    json.Unmarshal(dd, d2)    fmt.Println(d2)}这是它产生的输出{2019-05-20 15:20:16.247914 +0530 IST}{0001-01-01 00:00:00 +0000 UTC}第一行是原始时间,第二行是解组后的时间。为什么我们会因转换而丢失这种信息JSON?如何防止这种情况?谢谢。
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

Go vet 会准确告诉您问题出在哪里:

./prog.go:18:16: Unmarshal 的调用将非指针作为第二个参数传递

永远不要忽略错误!您至少可以打印它:

ds := check{A: time.Now().Truncate(0)}

fmt.Println(ds)

dd, err := json.Marshal(ds)

fmt.Println(err)

d2 := check{}

err = json.Unmarshal(dd, d2)

fmt.Println(err)

fmt.Println(d2)

这将输出(在Go Playground上尝试):

{2009-11-10 23:00:00 +0000 UTC}

<nil>

json: Unmarshal(non-pointer main.check)

{0001-01-01 00:00:00 +0000 UTC}

您必须传递一个指针才能json.Unmarshal()将其解组为(更改)您的值:

err = json.Unmarshal(dd, &d2)

使用此更改输出将是(在Go Playground上尝试):

{2009-11-10 23:00:00 +0000 UTC}
<nil>
<nil>
{2009-11-10 23:00:00 +0000 UTC}


查看完整回答
反对 回复 2023-06-19
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信