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.
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}