gpt4 book ai didi

flutter - 如何将 Flutter iso8601 DateTime 解码为 Go Api RFC3339 pgtype.Date 和 pgtype.Timestamptz

转载 作者:行者123 更新时间:2023-12-05 03:26:28 25 4
gpt4 key购买 nike

在我的 Go API 中,我尝试使用 json 解码来解析以下 json。

{"contract_id":0,"date_established":"2022-04-03T00:00:00.000","expiry_date":null,"extension_expiry_date":null,"description":"fffff"}

我得到一个错误:

parsing time "\"2022-04-03T00:00:00.000\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "\"" as "Z07:00"

我该如何修复这个错误?

这是我的结构:

// Contract model
type Contract struct {
ContractId *int `json:"contract_id"`
CompanyId *int `json:"company_id"`
DateEstablished *time.Time `json:"date_established"`
ExpiryDate *time.Time `json:"expiry_date"`
ExtensionExpiryDate *time.Time `json:"extension_expiry_date"`
Description *string `json:"description"`
}

这是我的代码:

func (rs *appResource) contractCreate(w http.ResponseWriter, r *http.Request) {

var contract Contract

decoder := json.NewDecoder(r.Body)

err = decoder.Decode(&contract)

最佳答案

Go 使用 RFC 3339 编码时间,如果您控制生成的 json,您只需将 2022-04-03T00:00:00.000 更改为 2022-04-03T00:00 :00.000Z.

例如这行得通。

type Contract struct {
ContractId *int `json:"contract_id"`
CompanyId *int `json:"company_id"`
DateEstablished *time.Time `json:"date_established"`
ExpiryDate *time.Time `json:"expiry_date"`
ExtensionExpiryDate *time.Time `json:"extension_expiry_date"`
Description *string `json:"description"`
}

func main() {
body := `{"contract_id":0,"date_established":"2022-04-03T00:00:00.000Z","expiry_date":null,"extension_expiry_date":null,"description":"fffff"}`

var contract Contract
reader := strings.NewReader(body)
decoder := json.NewDecoder(reader)
err := decoder.Decode(&contract)
if err != nil {
fmt.Println("Error: ", err)
} else {
fmt.Printf("Contract: %+v\n", contract)
}
}

如果不控制json,需要自己写一个自定义的unmarshal method .

关于flutter - 如何将 Flutter iso8601 DateTime 解码为 Go Api RFC3339 pgtype.Date 和 pgtype.Timestamptz,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71723032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com