解封时间.Time会改变响应。

huangapple go评论67阅读模式
英文:

Unmarshalling time.Time changes the response

问题

我正在从服务器获取一些数据并对JSON进行解组。当我将日期时间字符串转换为time.Time类型时,解组后的对象被截断了,而且日期也是错误的。这可能是一个提示。

我开始将时间转换为字符串:

type History struct {
    Id      string
    Created string
    Items   []HistoryItem
}

var response []History
json.Unmarshal([]byte(s), &response)

这样做很好,我得到了一个类似这样的列表:

[{91096 2021-06-04T10:28:21.179-0400 [{Rank  Ranked higher}]} {91078 2021-06-04T09:49:28.630-0400 [{Target end  8/Jun/21}]} //...etc

但是当我尝试将其转换为Time类型时:

type History struct {
    Id      string
    Created time.Time
    Items   []HistoryItem
}

我只得到了一个单独的项,而且时间明显是错误的。该对象中也没有其他值。

[{91096 0001-01-01 00:00:00 +0000 UTC []}]

实际的JSON表示如下:

"created": "2021-06-04T10:28:21.179-0400",
英文:

I'm getting some data from a server and Un-Marshalling the JSON. When I cast the datetime string to a string, I get all my results as an Un-Marshalled object, but when I type it as time.Time, the rest of the object is cut short. Also, the date is wrong, which might be a hint.

I started casting the time to a string:

type History struct {
	Id      string
	Created string
	Items   []HistoryItem
}

	var response []History
	json.Unmarshal([]byte(s), &response)

Which is great, I get back a list like this:

[{91096 2021-06-04T10:28:21.179-0400 [{Rank  Ranked higher}]} {91078 2021-06-04T09:49:28.630-0400 [{Target end  8/Jun/21}]} //...etc

But when I try to cast it as Time:

type History struct {
	Id      string
	Created time.Time
	Items   []HistoryItem
}

I get a single item and it's clearly the wrong time. No other values in that object either.

[{91096 0001-01-01 00:00:00 +0000 UTC []}]

The actual JSON representations look like this:

"created": "2021-06-04T10:28:21.179-0400",

答案1

得分: 2

"2021-06-04T10:28:21.179-0400"这个时间不符合识别的格式。你需要自己解析它。你可以使用以下格式进行解析:

t, err := time.Parse("2006-01-02T15:04:05.999999999-0700", "2021-06-04T10:28:21.179-0400")
英文:

The time "2021-06-04T10:28:21.179-0400" is not in a recognized format. You have to parse it yourself. You can use this format to parse it:

t, err:=time.Parse("2006-01-02T15:04:05.999999999-0700","2021-06-04T10:28:21.179-0400")

huangapple
  • 本文由 发表于 2021年6月7日 08:35:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/67864756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定