我有一个奇怪的问题。我正在使用echo
包进行路由。我将json
解码为struct
时遇到错误parsing time \"\"2019-01-02\"\" as \"\"2006-01-02T15:04:05Z07:00\"\": cannot parse \"\"\" as \"T\""
我的结构
VendorAgreement struct {
ID primitive.ObjectID `json:"id" bson:"_id"`
StartDate time.Time `json:"start_date,date" bson:"start_date"`
EndDate time.Time `json:"end_date,date" bson:"end_date"`
CommissionPercentage float32 `json:"commission_percentage" bson:"commission_percentage"`
Status int `json:"status" bson:"status"`
CreatedDate time.Time `json:"created_date" bson:"created_date"`
Media VendorAgreementMedia `json:"media" bson:"media"`
}
VendorAgreementMedia struct {
MediaId primitive.ObjectID `json:"mediaId" bson:"_id"`
FileName string `json:"file_name" bson:"file_name"`
SourcePath string `json:"source_path" bson:"source_path"`
CreatedDate time.Time `json:"created_date" bson:"created_date"`
}
我的解码步骤
var agreement VendorAgreement
err = json.NewDecoder(c.Request().Body).Decode(&agreement)
请求正文
{
"start_date":"2019-01-02",
"end_date":"2020-05-06",
"commission_percentage":10,
"media":{
"mediaId":"5cd1644cc57849f0761632b5"
}
}
答案 0 :(得分:1)
您需要具有自定义时间类型才能解组自定义时间格式:
type Datetime struct {
time.Time
}
func (t *Datetime) UnmarshalJSON(input []byte) error {
strInput := strings.Trim(string(input), `"`)
newTime, err := time.Parse("2006-01-02", strInput)
if err != nil {
return err
}
t.Time = newTime
return nil
}
VendorAgreement struct {
ID primitive.ObjectID `json:"id" bson:"_id"`
StartDate Datetime `json:"start_date,date" bson:"start_date"`
EndDate Datetime `json:"end_date,date" bson:"end_date"`
CommissionPercentage float32 `json:"commission_percentage" bson:"commission_percentage"`
Status int `json:"status" bson:"status"`
CreatedDate Datetime `json:"created_date" bson:"created_date"`
Media VendorAgreementMedia `json:"media" bson:"media"`
}
VendorAgreementMedia struct {
MediaId primitive.ObjectID `json:"mediaId" bson:"_id"`
FileName string `json:"file_name" bson:"file_name"`
SourcePath string `json:"source_path" bson:"source_path"`
CreatedDate Datetime `json:"created_date" bson:"created_date"`
}
答案 1 :(得分:0)
您可以像这样解析mongo返回的日期:
layout := "2006-01-02T15:04:05.999999999Z07:00"
str := "2019-01-02T00:00:00.000Z"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(t)
}