栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

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

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/905849.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号