douhao2011
2017-07-25 12:28
浏览 343
已采纳

如何从Golang中的json解析非标准时间格式?

lets say i have the following json

{
    name: "John",
    birth_date: "1996-10-07"
}

and i want to decode it into the following structure

type Person struct {
    Name string `json:"name"`
    BirthDate time.Time `json:"birth_date"`
}

like this

person := Person{}

decoder := json.NewDecoder(req.Body);

if err := decoder.Decode(&person); err != nil {
    log.Println(err)
}

which gives me the error parsing time ""1996-10-07"" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "T"

if i were to parse it manually i would do it like this

t, err := time.Parse("2006-01-02", "1996-10-07")

but when the time value is from a json string how do i get the decoder to parse it in the above format?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • dsy19811981 2017-07-25 12:59
    最佳回答

    That's a case when you need to implement custom marshal und unmarshal functions.

    UnmarshalJSON(b []byte) error { ... }
    
    MarshalJSON() ([]byte, error) { ... }
    

    By following the example in the Golang documentation of json package you get something like:

    // 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)
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题