parsing time ““““ as ““2006-01-02T15:04:05Z07:00““: cannot parse “““ as “2006“

parsing time ““““ as ““2006-01-02T15:04:05Z07:00““: cannot parse “““ as “2006“,第1张

I encounter the below error when I want to parse such string to struct.
parsing time “”"" as ““2006-01-02T15:04:05Z07:00"”: cannot parse “”” as "2006"

package main

import (
	"fmt"
	"time"
	"encoding/json"
)

func main() {
	s :=`[
	{"name":"test1","expireAt":"2050-12-31T00:00:00Z"},
	{"name":"test2","expireAt":""}
	]`
	var result []struct{
		Name string
		ExpireAt time.Time 
	}
	err :=json.Unmarshal([]byte(s),&result)
	if err!=nil{
	  fmt.Println(err)
	}
	for _,v :=range result{
	fmt.Println(v.ExpireAt)
	}
}

Output:

parsing time "\"\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "\"" as "2006"
2050-12-31 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

Solution:

package main

import (
	"fmt"
	"time"
	"encoding/json"
)
type MyTime time.Time

func (m *MyTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" || string(data) == `""` {
		return nil
	}
	return json.Unmarshal(data, (*time.Time)(m))
}

func main() {
	s :=`[
	{"name":"test1","expireAt":"2050-12-31T00:00:00Z"},
	{"name":"test2","expireAt":""}
	]`
	var result []struct{
		Name string
		ExpireAt MyTime 
	}
	err :=json.Unmarshal([]byte(s),&result)
	if err!=nil{
	  fmt.Println(err)
	}
	for _,v :=range result{
	fmt.Println(time.Time(v.ExpireAt))
	}
}

Output:

2050-12-31 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

BTW, there is one more point that I hope to get you guy’s attention. The point is that it can work fine if we ignore the error when we unmarshal the string to the struct.
For example:

package main

import (
	"encoding/json"
	"fmt"
	"time"
)

func main() {
	s := `[
	{"name":"test1","expireAt":"2050-12-31T00:00:00Z"},
	{"name":"test2"}
	]`
	var result []struct {
		Name     string
		ExpireAt time.Time
	}
	_ = json.Unmarshal([]byte(s), &result)
	for _, v := range result {
		fmt.Println(v.ExpireAt)
	}
}

Output

2050-12-31 00:00:00 +0000 UTC
0001-01-01 00:00:00 +0000 UTC

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994784.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存