How to parse non standard time format from json

后端 未结 3 1517
梦如初夏
梦如初夏 2020-12-24 03:32

lets say i have the following json

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

and i want to decode it into the following struct

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 03:50

    That's a case when you need to implement custom marshal and 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"`
    }
    
    // Implement Marshaler and Unmarshaler 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)
    }
    

提交回复
热议问题