dongluo8439 2019-05-20 09:56
浏览 445
已采纳

时间JSON封送至0时间

I have the following code which primarily marshals and un-marshals a time struct. Here is the code

package main

import (
    "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)
}

here is the output it produces

{2019-05-20 15:20:16.247914 +0530 IST}
{0001-01-01 00:00:00 +0000 UTC}

The first line is the original time and the second line is the time after the unmarshalling. Why do we have this loss of information with JSON conversions? How to prevent this? Thanks.

  • 写回答

1条回答 默认 最新

  • douan4347 2019-05-20 10:00
    关注

    Go vet tells you exactly what the problem is:

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

    Also never ignore errors! The least you can do is print it:

    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)
    

    This will output (try it on the 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}
    

    You have to pass a pointer to json.Unmarshal() for it to be able to unmarshal into (change) your value:

    err = json.Unmarshal(dd, &d2)
    

    With this change output will be (try it on the Go Playground):

    {2009-11-10 23:00:00 +0000 UTC}
    <nil>
    <nil>
    {2009-11-10 23:00:00 +0000 UTC}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序