可以说我有以下json
{ name: "John", birth_date: "1996-10-07" }
我想将其解码为以下结构
type Person struct { Name string `json:"name"` BirthDate time.Time `json:"birth_date"` }
像这样
person := Person{} decoder := json.NewDecoder(req.Body); if err := decoder.Decode(&person); err != nil { log.Println(err) }
这给了我错误 parsing time ""1996-10-07"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"
parsing time ""1996-10-07"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"
如果我要手动解析它,我会这样做
t, err := time.Parse("2006-01-02", "1996-10-07")
但是,当时间值来自json字符串时 ,我如何使解码器以上述格式解析它?
在这种情况下,您需要实现自定义编组和非编组功能。
UnmarshalJSON(b []byte) error { ... } MarshalJSON() ([]byte, error) { ... }
通过遵循json包的Golang文档中的示例,您将获得以下内容:
// first create a type alias type JsonBirthDate time.Time // Add that to your struct type Person struct { Name string `json:"name"` BirthDate JsonBirthDate `json:"birth_date"` } // imeplement Marshaler und Unmarshalere interface func (j *JsonBirthDate) UnmarshalJSON(b []byte) error { s := strings.Trim(string(b), "\"") t, err := time.Parse("2006-01-02", s) if err != nil { return err } *j = JsonBirthDate(t) return nil } func (j JsonBirthDate) MarshalJSON() ([]byte, error) { return json.Marshal(j) } // Maybe a Format function for printing your date func (j JsonBirthDate) Format(s string) string { t := time.Time(j) return t.Format(s) }