请求正文日期解析问题

时间:2019-05-07 13:07:32

标签: json date go echo-framework

我有一个奇怪的问题。我正在使用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"
    }
}

2 个答案:

答案 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)
}