sách gpt4 ăn đã đi

json - 时间 JSON 编码为 0 时间

In lại 作者:数据小太阳 更新时间:2023-10-29 03:38:31 34 4
mua khóa gpt4 giày nike

我有以下代码,主要编码和取消编码时间结构。这是代码

gói chính

nhập khẩu (
"fmt"
"thời gian"
"encoding/json"
)

type check struct{
A time.Time `json:"a"`
}

hàm 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 转换中会丢失这种信息?如何防止这种情况?谢谢。

câu trả lời hay nhất

Go vet 会告诉您到底是什么问题:

./prog.go:18:16: call of Unmarshal passes non-pointer as second argument

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

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)

这将输出(在 Đi đến Sân chơi 上尝试):

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

json: Unmarshal(non-pointer main.check)
{0001-01-01 00:00:00 +0000 UTC}

你必须传递一个con trỏjson.Unmarshal()使其能够解码为(更改)您的值:

err = json.Unmarshal(dd, &d2)

此更改输出将是(在 Đi đến Sân chơi 上尝试):

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


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

关于json - 时间 JSON 编码为 0 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56218468/

34 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress