如何从golang中解析json的非标准时间格式?
可以说,我有以下的JSON如何从golang中解析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"
如果我要解析它手动LY我会做这样的
t, err := time.Parse("2006-01-02", "1996-10-07")
但是当时间值是一个JSON字符串请问如何解码器解析它在上面的格式?
这是您需要实现自定义编组和解组函数的情况。
UnmarshalJSON(b []byte) error { ... }
MarshalJSON() ([]byte, error) { ... }
通过以下json package的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 = JB(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)
}
Right ,对于'UnmarshalJSON'函数,OP可以根据需要支持的不同格式添加多个'time.Parse'尝试。我相信'time.RFC3339'的格式是默认的解析器,更多的格式可以在[docs](https://golang.org/pkg/time/#pkg-constants) – Jonathan
找到。当然,当你有自定义联合国/主管职能,你应该尽量涵盖每一个可能的情况。 – Kiril
Minor nit:根据[code style](https://github.com/golang/go/wiki/CodeReviewComments#initialisms),它应该是'JSONBirthDate',而不是'JsonBirthDate'。 –
[解析陶醉一个JSON日期时间(可能的重复https://stackoverflow.com/questions/ 44705817/parsing-a-json-date-in-revel) – RickyA
[在golang中解析日期字符串]可能的副本(https://stackoverflow.com/questions/25845172/parsing-date-string-in-golang) – Adrian